1 //== RetainSummaryManager.cpp - Summaries for reference counting --*- C++ -*--// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines summaries implementation for retain counting, which 10 // implements a reference count checker for Core Foundation, Cocoa 11 // and OSObject (on Mac OS X). 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Analysis/DomainSpecific/CocoaConventions.h" 16 #include "clang/Analysis/RetainSummaryManager.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/ParentMap.h" 21 #include "clang/ASTMatchers/ASTMatchFinder.h" 22 23 using namespace clang; 24 using namespace ento; 25 26 template <class T> 27 constexpr static bool isOneOf() { 28 return false; 29 } 30 31 /// Helper function to check whether the class is one of the 32 /// rest of varargs. 33 template <class T, class P, class... ToCompare> 34 constexpr static bool isOneOf() { 35 return std::is_same<T, P>::value || isOneOf<T, ToCompare...>(); 36 } 37 38 namespace { 39 40 /// Fake attribute class for RC* attributes. 41 struct GeneralizedReturnsRetainedAttr { 42 static bool classof(const Attr *A) { 43 if (auto AA = dyn_cast<AnnotateAttr>(A)) 44 return AA->getAnnotation() == "rc_ownership_returns_retained"; 45 return false; 46 } 47 }; 48 49 struct GeneralizedReturnsNotRetainedAttr { 50 static bool classof(const Attr *A) { 51 if (auto AA = dyn_cast<AnnotateAttr>(A)) 52 return AA->getAnnotation() == "rc_ownership_returns_not_retained"; 53 return false; 54 } 55 }; 56 57 struct GeneralizedConsumedAttr { 58 static bool classof(const Attr *A) { 59 if (auto AA = dyn_cast<AnnotateAttr>(A)) 60 return AA->getAnnotation() == "rc_ownership_consumed"; 61 return false; 62 } 63 }; 64 65 } 66 67 template <class T> 68 Optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D, 69 QualType QT) { 70 ObjKind K; 71 if (isOneOf<T, CFConsumedAttr, CFReturnsRetainedAttr, 72 CFReturnsNotRetainedAttr>()) { 73 if (!TrackObjCAndCFObjects) 74 return None; 75 76 K = ObjKind::CF; 77 } else if (isOneOf<T, NSConsumedAttr, NSConsumesSelfAttr, 78 NSReturnsAutoreleasedAttr, NSReturnsRetainedAttr, 79 NSReturnsNotRetainedAttr, NSConsumesSelfAttr>()) { 80 81 if (!TrackObjCAndCFObjects) 82 return None; 83 84 if (isOneOf<T, NSReturnsRetainedAttr, NSReturnsAutoreleasedAttr, 85 NSReturnsNotRetainedAttr>() && 86 !cocoa::isCocoaObjectRef(QT)) 87 return None; 88 K = ObjKind::ObjC; 89 } else if (isOneOf<T, OSConsumedAttr, OSConsumesThisAttr, 90 OSReturnsNotRetainedAttr, OSReturnsRetainedAttr, 91 OSReturnsRetainedOnZeroAttr, 92 OSReturnsRetainedOnNonZeroAttr>()) { 93 if (!TrackOSObjects) 94 return None; 95 K = ObjKind::OS; 96 } else if (isOneOf<T, GeneralizedReturnsNotRetainedAttr, 97 GeneralizedReturnsRetainedAttr, 98 GeneralizedConsumedAttr>()) { 99 K = ObjKind::Generalized; 100 } else { 101 llvm_unreachable("Unexpected attribute"); 102 } 103 if (D->hasAttr<T>()) 104 return K; 105 return None; 106 } 107 108 template <class T1, class T2, class... Others> 109 Optional<ObjKind> RetainSummaryManager::hasAnyEnabledAttrOf(const Decl *D, 110 QualType QT) { 111 if (auto Out = hasAnyEnabledAttrOf<T1>(D, QT)) 112 return Out; 113 return hasAnyEnabledAttrOf<T2, Others...>(D, QT); 114 } 115 116 const RetainSummary * 117 RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) { 118 // Unique "simple" summaries -- those without ArgEffects. 119 if (OldSumm.isSimple()) { 120 ::llvm::FoldingSetNodeID ID; 121 OldSumm.Profile(ID); 122 123 void *Pos; 124 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos); 125 126 if (!N) { 127 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>(); 128 new (N) CachedSummaryNode(OldSumm); 129 SimpleSummaries.InsertNode(N, Pos); 130 } 131 132 return &N->getValue(); 133 } 134 135 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>(); 136 new (Summ) RetainSummary(OldSumm); 137 return Summ; 138 } 139 140 static bool isSubclass(const Decl *D, 141 StringRef ClassName) { 142 using namespace ast_matchers; 143 DeclarationMatcher SubclassM = cxxRecordDecl(isSameOrDerivedFrom(ClassName)); 144 return !(match(SubclassM, *D, D->getASTContext()).empty()); 145 } 146 147 static bool isOSObjectSubclass(const Decl *D) { 148 return isSubclass(D, "OSMetaClassBase"); 149 } 150 151 static bool isOSObjectDynamicCast(StringRef S) { 152 return S == "safeMetaCast"; 153 } 154 155 static bool isOSObjectThisCast(StringRef S) { 156 return S == "metaCast"; 157 } 158 159 static bool isOSIteratorSubclass(const Decl *D) { 160 return isSubclass(D, "OSIterator"); 161 } 162 163 static bool hasRCAnnotation(const Decl *D, StringRef rcAnnotation) { 164 for (const auto *Ann : D->specific_attrs<AnnotateAttr>()) { 165 if (Ann->getAnnotation() == rcAnnotation) 166 return true; 167 } 168 return false; 169 } 170 171 static bool isRetain(const FunctionDecl *FD, StringRef FName) { 172 return FName.startswith_lower("retain") || FName.endswith_lower("retain"); 173 } 174 175 static bool isRelease(const FunctionDecl *FD, StringRef FName) { 176 return FName.startswith_lower("release") || FName.endswith_lower("release"); 177 } 178 179 static bool isAutorelease(const FunctionDecl *FD, StringRef FName) { 180 return FName.startswith_lower("autorelease") || 181 FName.endswith_lower("autorelease"); 182 } 183 184 static bool isMakeCollectable(StringRef FName) { 185 return FName.contains_lower("MakeCollectable"); 186 } 187 188 /// A function is OSObject related if it is declared on a subclass 189 /// of OSObject, or any of the parameters is a subclass of an OSObject. 190 static bool isOSObjectRelated(const CXXMethodDecl *MD) { 191 if (isOSObjectSubclass(MD->getParent())) 192 return true; 193 194 for (ParmVarDecl *Param : MD->parameters()) { 195 QualType PT = Param->getType()->getPointeeType(); 196 if (!PT.isNull()) 197 if (CXXRecordDecl *RD = PT->getAsCXXRecordDecl()) 198 if (isOSObjectSubclass(RD)) 199 return true; 200 } 201 202 return false; 203 } 204 205 bool 206 RetainSummaryManager::isKnownSmartPointer(QualType QT) { 207 QT = QT.getCanonicalType(); 208 const auto *RD = QT->getAsCXXRecordDecl(); 209 if (!RD) 210 return false; 211 const IdentifierInfo *II = RD->getIdentifier(); 212 if (II && II->getName() == "smart_ptr") 213 if (const auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext())) 214 if (ND->getNameAsString() == "os") 215 return true; 216 return false; 217 } 218 219 const RetainSummary * 220 RetainSummaryManager::getSummaryForOSObject(const FunctionDecl *FD, 221 StringRef FName, QualType RetTy) { 222 if (RetTy->isPointerType()) { 223 const CXXRecordDecl *PD = RetTy->getPointeeType()->getAsCXXRecordDecl(); 224 if (PD && isOSObjectSubclass(PD)) { 225 if (const IdentifierInfo *II = FD->getIdentifier()) { 226 StringRef FuncName = II->getName(); 227 if (isOSObjectDynamicCast(FuncName) || isOSObjectThisCast(FuncName)) 228 return getDefaultSummary(); 229 230 // All objects returned with functions *not* starting with 231 // get, or iterators, are returned at +1. 232 if ((!FuncName.startswith("get") && !FuncName.startswith("Get")) || 233 isOSIteratorSubclass(PD)) { 234 return getOSSummaryCreateRule(FD); 235 } else { 236 return getOSSummaryGetRule(FD); 237 } 238 } 239 } 240 } 241 242 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 243 const CXXRecordDecl *Parent = MD->getParent(); 244 if (TrackOSObjects && Parent && isOSObjectSubclass(Parent)) { 245 if (FName == "release" || FName == "taggedRelease") 246 return getOSSummaryReleaseRule(FD); 247 248 if (FName == "retain" || FName == "taggedRetain") 249 return getOSSummaryRetainRule(FD); 250 251 if (FName == "free") 252 return getOSSummaryFreeRule(FD); 253 254 if (MD->getOverloadedOperator() == OO_New) 255 return getOSSummaryCreateRule(MD); 256 } 257 } 258 259 return nullptr; 260 } 261 262 const RetainSummary *RetainSummaryManager::getSummaryForObjCOrCFObject( 263 const FunctionDecl *FD, 264 StringRef FName, 265 QualType RetTy, 266 const FunctionType *FT, 267 bool &AllowAnnotations) { 268 269 ArgEffects ScratchArgs(AF.getEmptyMap()); 270 271 std::string RetTyName = RetTy.getAsString(); 272 if (FName == "pthread_create" || FName == "pthread_setspecific") { 273 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>. 274 // This will be addressed better with IPA. 275 return getPersistentStopSummary(); 276 } else if(FName == "NSMakeCollectable") { 277 // Handle: id NSMakeCollectable(CFTypeRef) 278 AllowAnnotations = false; 279 return RetTy->isObjCIdType() ? getUnarySummary(FT, DoNothing) 280 : getPersistentStopSummary(); 281 } else if (FName == "CMBufferQueueDequeueAndRetain" || 282 FName == "CMBufferQueueDequeueIfDataReadyAndRetain") { 283 // Part of: <rdar://problem/39390714>. 284 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), 285 ScratchArgs, 286 ArgEffect(DoNothing), 287 ArgEffect(DoNothing)); 288 } else if (FName == "CFPlugInInstanceCreate") { 289 return getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs); 290 } else if (FName == "IORegistryEntrySearchCFProperty" || 291 (RetTyName == "CFMutableDictionaryRef" && 292 (FName == "IOBSDNameMatching" || FName == "IOServiceMatching" || 293 FName == "IOServiceNameMatching" || 294 FName == "IORegistryEntryIDMatching" || 295 FName == "IOOpenFirmwarePathMatching"))) { 296 // Part of <rdar://problem/6961230>. (IOKit) 297 // This should be addressed using a API table. 298 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs, 299 ArgEffect(DoNothing), ArgEffect(DoNothing)); 300 } else if (FName == "IOServiceGetMatchingService" || 301 FName == "IOServiceGetMatchingServices") { 302 // FIXES: <rdar://problem/6326900> 303 // This should be addressed using a API table. This strcmp is also 304 // a little gross, but there is no need to super optimize here. 305 ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(DecRef, ObjKind::CF)); 306 return getPersistentSummary(RetEffect::MakeNoRet(), 307 ScratchArgs, 308 ArgEffect(DoNothing), ArgEffect(DoNothing)); 309 } else if (FName == "IOServiceAddNotification" || 310 FName == "IOServiceAddMatchingNotification") { 311 // Part of <rdar://problem/6961230>. (IOKit) 312 // This should be addressed using a API table. 313 ScratchArgs = AF.add(ScratchArgs, 2, ArgEffect(DecRef, ObjKind::CF)); 314 return getPersistentSummary(RetEffect::MakeNoRet(), 315 ScratchArgs, 316 ArgEffect(DoNothing), ArgEffect(DoNothing)); 317 } else if (FName == "CVPixelBufferCreateWithBytes") { 318 // FIXES: <rdar://problem/7283567> 319 // Eventually this can be improved by recognizing that the pixel 320 // buffer passed to CVPixelBufferCreateWithBytes is released via 321 // a callback and doing full IPA to make sure this is done correctly. 322 // FIXME: This function has an out parameter that returns an 323 // allocated object. 324 ScratchArgs = AF.add(ScratchArgs, 7, ArgEffect(StopTracking)); 325 return getPersistentSummary(RetEffect::MakeNoRet(), 326 ScratchArgs, 327 ArgEffect(DoNothing), ArgEffect(DoNothing)); 328 } else if (FName == "CGBitmapContextCreateWithData") { 329 // FIXES: <rdar://problem/7358899> 330 // Eventually this can be improved by recognizing that 'releaseInfo' 331 // passed to CGBitmapContextCreateWithData is released via 332 // a callback and doing full IPA to make sure this is done correctly. 333 ScratchArgs = AF.add(ScratchArgs, 8, ArgEffect(ArgEffect(StopTracking))); 334 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs, 335 ArgEffect(DoNothing), ArgEffect(DoNothing)); 336 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") { 337 // FIXES: <rdar://problem/7283567> 338 // Eventually this can be improved by recognizing that the pixel 339 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released 340 // via a callback and doing full IPA to make sure this is done 341 // correctly. 342 ScratchArgs = AF.add(ScratchArgs, 12, ArgEffect(StopTracking)); 343 return getPersistentSummary(RetEffect::MakeNoRet(), 344 ScratchArgs, 345 ArgEffect(DoNothing), ArgEffect(DoNothing)); 346 } else if (FName == "VTCompressionSessionEncodeFrame") { 347 // The context argument passed to VTCompressionSessionEncodeFrame() 348 // is passed to the callback specified when creating the session 349 // (e.g. with VTCompressionSessionCreate()) which can release it. 350 // To account for this possibility, conservatively stop tracking 351 // the context. 352 ScratchArgs = AF.add(ScratchArgs, 5, ArgEffect(StopTracking)); 353 return getPersistentSummary(RetEffect::MakeNoRet(), 354 ScratchArgs, 355 ArgEffect(DoNothing), ArgEffect(DoNothing)); 356 } else if (FName == "dispatch_set_context" || 357 FName == "xpc_connection_set_context") { 358 // <rdar://problem/11059275> - The analyzer currently doesn't have 359 // a good way to reason about the finalizer function for libdispatch. 360 // If we pass a context object that is memory managed, stop tracking it. 361 // <rdar://problem/13783514> - Same problem, but for XPC. 362 // FIXME: this hack should possibly go away once we can handle 363 // libdispatch and XPC finalizers. 364 ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(StopTracking)); 365 return getPersistentSummary(RetEffect::MakeNoRet(), 366 ScratchArgs, 367 ArgEffect(DoNothing), ArgEffect(DoNothing)); 368 } else if (FName.startswith("NSLog")) { 369 return getDoNothingSummary(); 370 } else if (FName.startswith("NS") && 371 (FName.find("Insert") != StringRef::npos)) { 372 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can 373 // be deallocated by NSMapRemove. (radar://11152419) 374 ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(StopTracking)); 375 ScratchArgs = AF.add(ScratchArgs, 2, ArgEffect(StopTracking)); 376 return getPersistentSummary(RetEffect::MakeNoRet(), 377 ScratchArgs, ArgEffect(DoNothing), 378 ArgEffect(DoNothing)); 379 } 380 381 if (RetTy->isPointerType()) { 382 383 // For CoreFoundation ('CF') types. 384 if (cocoa::isRefType(RetTy, "CF", FName)) { 385 if (isRetain(FD, FName)) { 386 // CFRetain isn't supposed to be annotated. However, this may as 387 // well be a user-made "safe" CFRetain function that is incorrectly 388 // annotated as cf_returns_retained due to lack of better options. 389 // We want to ignore such annotation. 390 AllowAnnotations = false; 391 392 return getUnarySummary(FT, IncRef); 393 } else if (isAutorelease(FD, FName)) { 394 // The headers use cf_consumed, but we can fully model CFAutorelease 395 // ourselves. 396 AllowAnnotations = false; 397 398 return getUnarySummary(FT, Autorelease); 399 } else if (isMakeCollectable(FName)) { 400 AllowAnnotations = false; 401 return getUnarySummary(FT, DoNothing); 402 } else { 403 return getCFCreateGetRuleSummary(FD); 404 } 405 } 406 407 // For CoreGraphics ('CG') and CoreVideo ('CV') types. 408 if (cocoa::isRefType(RetTy, "CG", FName) || 409 cocoa::isRefType(RetTy, "CV", FName)) { 410 if (isRetain(FD, FName)) 411 return getUnarySummary(FT, IncRef); 412 else 413 return getCFCreateGetRuleSummary(FD); 414 } 415 416 // For all other CF-style types, use the Create/Get 417 // rule for summaries but don't support Retain functions 418 // with framework-specific prefixes. 419 if (coreFoundation::isCFObjectRef(RetTy)) { 420 return getCFCreateGetRuleSummary(FD); 421 } 422 423 if (FD->hasAttr<CFAuditedTransferAttr>()) { 424 return getCFCreateGetRuleSummary(FD); 425 } 426 } 427 428 // Check for release functions, the only kind of functions that we care 429 // about that don't return a pointer type. 430 if (FName.startswith("CG") || FName.startswith("CF")) { 431 // Test for 'CGCF'. 432 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2); 433 434 if (isRelease(FD, FName)) 435 return getUnarySummary(FT, DecRef); 436 else { 437 assert(ScratchArgs.isEmpty()); 438 // Remaining CoreFoundation and CoreGraphics functions. 439 // We use to assume that they all strictly followed the ownership idiom 440 // and that ownership cannot be transferred. While this is technically 441 // correct, many methods allow a tracked object to escape. For example: 442 // 443 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...); 444 // CFDictionaryAddValue(y, key, x); 445 // CFRelease(x); 446 // ... it is okay to use 'x' since 'y' has a reference to it 447 // 448 // We handle this and similar cases with the follow heuristic. If the 449 // function name contains "InsertValue", "SetValue", "AddValue", 450 // "AppendValue", or "SetAttribute", then we assume that arguments may 451 // "escape." This means that something else holds on to the object, 452 // allowing it be used even after its local retain count drops to 0. 453 ArgEffectKind E = 454 (StrInStrNoCase(FName, "InsertValue") != StringRef::npos || 455 StrInStrNoCase(FName, "AddValue") != StringRef::npos || 456 StrInStrNoCase(FName, "SetValue") != StringRef::npos || 457 StrInStrNoCase(FName, "AppendValue") != StringRef::npos || 458 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos) 459 ? MayEscape 460 : DoNothing; 461 462 return getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs, 463 ArgEffect(DoNothing), ArgEffect(E, ObjKind::CF)); 464 } 465 } 466 467 return nullptr; 468 } 469 470 const RetainSummary * 471 RetainSummaryManager::generateSummary(const FunctionDecl *FD, 472 bool &AllowAnnotations) { 473 // We generate "stop" summaries for implicitly defined functions. 474 if (FD->isImplicit()) 475 return getPersistentStopSummary(); 476 477 const IdentifierInfo *II = FD->getIdentifier(); 478 479 StringRef FName = II ? II->getName() : ""; 480 481 // Strip away preceding '_'. Doing this here will effect all the checks 482 // down below. 483 FName = FName.substr(FName.find_first_not_of('_')); 484 485 // Inspect the result type. Strip away any typedefs. 486 const auto *FT = FD->getType()->getAs<FunctionType>(); 487 QualType RetTy = FT->getReturnType(); 488 489 if (TrackOSObjects) 490 if (const RetainSummary *S = getSummaryForOSObject(FD, FName, RetTy)) 491 return S; 492 493 if (TrackObjCAndCFObjects) 494 if (const RetainSummary *S = 495 getSummaryForObjCOrCFObject(FD, FName, RetTy, FT, AllowAnnotations)) 496 return S; 497 498 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 499 if (!(TrackOSObjects && isOSObjectRelated(MD))) 500 return getPersistentSummary(RetEffect::MakeNoRet(), 501 ArgEffects(AF.getEmptyMap()), 502 ArgEffect(DoNothing), 503 ArgEffect(StopTracking), 504 ArgEffect(DoNothing)); 505 506 return getDefaultSummary(); 507 } 508 509 const RetainSummary * 510 RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) { 511 // If we don't know what function we're calling, use our default summary. 512 if (!FD) 513 return getDefaultSummary(); 514 515 // Look up a summary in our cache of FunctionDecls -> Summaries. 516 FuncSummariesTy::iterator I = FuncSummaries.find(FD); 517 if (I != FuncSummaries.end()) 518 return I->second; 519 520 // No summary? Generate one. 521 bool AllowAnnotations = true; 522 const RetainSummary *S = generateSummary(FD, AllowAnnotations); 523 524 // Annotations override defaults. 525 if (AllowAnnotations) 526 updateSummaryFromAnnotations(S, FD); 527 528 FuncSummaries[FD] = S; 529 return S; 530 } 531 532 //===----------------------------------------------------------------------===// 533 // Summary creation for functions (largely uses of Core Foundation). 534 //===----------------------------------------------------------------------===// 535 536 static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) { 537 switch (E.getKind()) { 538 case DoNothing: 539 case Autorelease: 540 case DecRefBridgedTransferred: 541 case IncRef: 542 case UnretainedOutParameter: 543 case RetainedOutParameter: 544 case RetainedOutParameterOnZero: 545 case RetainedOutParameterOnNonZero: 546 case MayEscape: 547 case StopTracking: 548 case StopTrackingHard: 549 return E.withKind(StopTrackingHard); 550 case DecRef: 551 case DecRefAndStopTrackingHard: 552 return E.withKind(DecRefAndStopTrackingHard); 553 case Dealloc: 554 return E.withKind(Dealloc); 555 } 556 557 llvm_unreachable("Unknown ArgEffect kind"); 558 } 559 560 const RetainSummary * 561 RetainSummaryManager::updateSummaryForNonZeroCallbackArg(const RetainSummary *S, 562 AnyCall &C) { 563 ArgEffect RecEffect = getStopTrackingHardEquivalent(S->getReceiverEffect()); 564 ArgEffect DefEffect = getStopTrackingHardEquivalent(S->getDefaultArgEffect()); 565 566 ArgEffects ScratchArgs(AF.getEmptyMap()); 567 ArgEffects CustomArgEffects = S->getArgEffects(); 568 for (ArgEffects::iterator I = CustomArgEffects.begin(), 569 E = CustomArgEffects.end(); 570 I != E; ++I) { 571 ArgEffect Translated = getStopTrackingHardEquivalent(I->second); 572 if (Translated.getKind() != DefEffect.getKind()) 573 ScratchArgs = AF.add(ScratchArgs, I->first, Translated); 574 } 575 576 RetEffect RE = RetEffect::MakeNoRetHard(); 577 578 // Special cases where the callback argument CANNOT free the return value. 579 // This can generally only happen if we know that the callback will only be 580 // called when the return value is already being deallocated. 581 if (const IdentifierInfo *Name = C.getIdentifier()) { 582 // When the CGBitmapContext is deallocated, the callback here will free 583 // the associated data buffer. 584 // The callback in dispatch_data_create frees the buffer, but not 585 // the data object. 586 if (Name->isStr("CGBitmapContextCreateWithData") || 587 Name->isStr("dispatch_data_create")) 588 RE = S->getRetEffect(); 589 } 590 591 return getPersistentSummary(RE, ScratchArgs, RecEffect, DefEffect); 592 } 593 594 void RetainSummaryManager::updateSummaryForReceiverUnconsumedSelf( 595 const RetainSummary *&S) { 596 597 RetainSummaryTemplate Template(S, *this); 598 599 Template->setReceiverEffect(ArgEffect(DoNothing)); 600 Template->setRetEffect(RetEffect::MakeNoRet()); 601 } 602 603 const RetainSummary * 604 RetainSummaryManager::getSummary(AnyCall C, 605 bool HasNonZeroCallbackArg, 606 bool IsReceiverUnconsumedSelf, 607 QualType ReceiverType) { 608 const RetainSummary *Summ; 609 switch (C.getKind()) { 610 case AnyCall::Function: 611 case AnyCall::Constructor: 612 case AnyCall::Allocator: 613 case AnyCall::Deallocator: 614 Summ = getFunctionSummary(cast_or_null<FunctionDecl>(C.getDecl())); 615 break; 616 case AnyCall::Block: 617 case AnyCall::Destructor: 618 // FIXME: These calls are currently unsupported. 619 return getPersistentStopSummary(); 620 case AnyCall::ObjCMethod: { 621 const auto *ME = cast_or_null<ObjCMessageExpr>(C.getExpr()); 622 if (!ME) { 623 return getMethodSummary(cast<ObjCMethodDecl>(C.getDecl())); 624 } else if (ME->isInstanceMessage()) { 625 Summ = getInstanceMethodSummary(ME, ReceiverType); 626 } else { 627 Summ = getClassMethodSummary(ME); 628 } 629 break; 630 } 631 } 632 633 if (HasNonZeroCallbackArg) 634 Summ = updateSummaryForNonZeroCallbackArg(Summ, C); 635 636 if (IsReceiverUnconsumedSelf) 637 updateSummaryForReceiverUnconsumedSelf(Summ); 638 639 assert(Summ && "Unknown call type?"); 640 return Summ; 641 } 642 643 644 const RetainSummary * 645 RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) { 646 if (coreFoundation::followsCreateRule(FD)) 647 return getCFSummaryCreateRule(FD); 648 649 return getCFSummaryGetRule(FD); 650 } 651 652 bool RetainSummaryManager::isTrustedReferenceCountImplementation( 653 const FunctionDecl *FD) { 654 return hasRCAnnotation(FD, "rc_ownership_trusted_implementation"); 655 } 656 657 Optional<RetainSummaryManager::BehaviorSummary> 658 RetainSummaryManager::canEval(const CallExpr *CE, const FunctionDecl *FD, 659 bool &hasTrustedImplementationAnnotation) { 660 661 IdentifierInfo *II = FD->getIdentifier(); 662 if (!II) 663 return None; 664 665 StringRef FName = II->getName(); 666 FName = FName.substr(FName.find_first_not_of('_')); 667 668 QualType ResultTy = CE->getCallReturnType(Ctx); 669 if (ResultTy->isObjCIdType()) { 670 if (II->isStr("NSMakeCollectable")) 671 return BehaviorSummary::Identity; 672 } else if (ResultTy->isPointerType()) { 673 // Handle: (CF|CG|CV)Retain 674 // CFAutorelease 675 // It's okay to be a little sloppy here. 676 if (FName == "CMBufferQueueDequeueAndRetain" || 677 FName == "CMBufferQueueDequeueIfDataReadyAndRetain") { 678 // Part of: <rdar://problem/39390714>. 679 // These are not retain. They just return something and retain it. 680 return None; 681 } 682 if (cocoa::isRefType(ResultTy, "CF", FName) || 683 cocoa::isRefType(ResultTy, "CG", FName) || 684 cocoa::isRefType(ResultTy, "CV", FName)) 685 if (isRetain(FD, FName) || isAutorelease(FD, FName) || 686 isMakeCollectable(FName)) 687 return BehaviorSummary::Identity; 688 689 // safeMetaCast is called by OSDynamicCast. 690 // We assume that OSDynamicCast is either an identity (cast is OK, 691 // the input was non-zero), 692 // or that it returns zero (when the cast failed, or the input 693 // was zero). 694 if (TrackOSObjects) { 695 if (isOSObjectDynamicCast(FName) && FD->param_size() >= 1) { 696 return BehaviorSummary::IdentityOrZero; 697 } else if (isOSObjectThisCast(FName) && isa<CXXMethodDecl>(FD) && 698 !cast<CXXMethodDecl>(FD)->isStatic()) { 699 return BehaviorSummary::IdentityThis; 700 } 701 } 702 703 const FunctionDecl* FDD = FD->getDefinition(); 704 if (FDD && isTrustedReferenceCountImplementation(FDD)) { 705 hasTrustedImplementationAnnotation = true; 706 return BehaviorSummary::Identity; 707 } 708 } 709 710 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 711 const CXXRecordDecl *Parent = MD->getParent(); 712 if (TrackOSObjects && Parent && isOSObjectSubclass(Parent)) 713 if (FName == "release" || FName == "retain") 714 return BehaviorSummary::NoOp; 715 } 716 717 return None; 718 } 719 720 const RetainSummary * 721 RetainSummaryManager::getUnarySummary(const FunctionType* FT, 722 ArgEffectKind AE) { 723 724 // Unary functions have no arg effects by definition. 725 ArgEffects ScratchArgs(AF.getEmptyMap()); 726 727 // Sanity check that this is *really* a unary function. This can 728 // happen if people do weird things. 729 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT); 730 if (!FTP || FTP->getNumParams() != 1) 731 return getPersistentStopSummary(); 732 733 ArgEffect Effect(AE, ObjKind::CF); 734 735 ScratchArgs = AF.add(ScratchArgs, 0, Effect); 736 return getPersistentSummary(RetEffect::MakeNoRet(), 737 ScratchArgs, 738 ArgEffect(DoNothing), ArgEffect(DoNothing)); 739 } 740 741 const RetainSummary * 742 RetainSummaryManager::getOSSummaryRetainRule(const FunctionDecl *FD) { 743 return getPersistentSummary(RetEffect::MakeNoRet(), 744 AF.getEmptyMap(), 745 /*ReceiverEff=*/ArgEffect(DoNothing), 746 /*DefaultEff=*/ArgEffect(DoNothing), 747 /*ThisEff=*/ArgEffect(IncRef, ObjKind::OS)); 748 } 749 750 const RetainSummary * 751 RetainSummaryManager::getOSSummaryReleaseRule(const FunctionDecl *FD) { 752 return getPersistentSummary(RetEffect::MakeNoRet(), 753 AF.getEmptyMap(), 754 /*ReceiverEff=*/ArgEffect(DoNothing), 755 /*DefaultEff=*/ArgEffect(DoNothing), 756 /*ThisEff=*/ArgEffect(DecRef, ObjKind::OS)); 757 } 758 759 const RetainSummary * 760 RetainSummaryManager::getOSSummaryFreeRule(const FunctionDecl *FD) { 761 return getPersistentSummary(RetEffect::MakeNoRet(), 762 AF.getEmptyMap(), 763 /*ReceiverEff=*/ArgEffect(DoNothing), 764 /*DefaultEff=*/ArgEffect(DoNothing), 765 /*ThisEff=*/ArgEffect(Dealloc, ObjKind::OS)); 766 } 767 768 const RetainSummary * 769 RetainSummaryManager::getOSSummaryCreateRule(const FunctionDecl *FD) { 770 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::OS), 771 AF.getEmptyMap()); 772 } 773 774 const RetainSummary * 775 RetainSummaryManager::getOSSummaryGetRule(const FunctionDecl *FD) { 776 return getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::OS), 777 AF.getEmptyMap()); 778 } 779 780 const RetainSummary * 781 RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) { 782 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), 783 ArgEffects(AF.getEmptyMap())); 784 } 785 786 const RetainSummary * 787 RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) { 788 return getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::CF), 789 ArgEffects(AF.getEmptyMap()), 790 ArgEffect(DoNothing), ArgEffect(DoNothing)); 791 } 792 793 794 795 796 //===----------------------------------------------------------------------===// 797 // Summary creation for Selectors. 798 //===----------------------------------------------------------------------===// 799 800 Optional<RetEffect> 801 RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy, 802 const Decl *D) { 803 if (hasAnyEnabledAttrOf<NSReturnsRetainedAttr>(D, RetTy)) 804 return ObjCAllocRetE; 805 806 if (auto K = hasAnyEnabledAttrOf<CFReturnsRetainedAttr, OSReturnsRetainedAttr, 807 GeneralizedReturnsRetainedAttr>(D, RetTy)) 808 return RetEffect::MakeOwned(*K); 809 810 if (auto K = hasAnyEnabledAttrOf< 811 CFReturnsNotRetainedAttr, OSReturnsNotRetainedAttr, 812 GeneralizedReturnsNotRetainedAttr, NSReturnsNotRetainedAttr, 813 NSReturnsAutoreleasedAttr>(D, RetTy)) 814 return RetEffect::MakeNotOwned(*K); 815 816 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) 817 for (const auto *PD : MD->overridden_methods()) 818 if (auto RE = getRetEffectFromAnnotations(RetTy, PD)) 819 return RE; 820 821 return None; 822 } 823 824 /// \return Whether the chain of typedefs starting from {@code QT} 825 /// has a typedef with a given name {@code Name}. 826 static bool hasTypedefNamed(QualType QT, 827 StringRef Name) { 828 while (auto *T = dyn_cast<TypedefType>(QT)) { 829 const auto &Context = T->getDecl()->getASTContext(); 830 if (T->getDecl()->getIdentifier() == &Context.Idents.get(Name)) 831 return true; 832 QT = T->getDecl()->getUnderlyingType(); 833 } 834 return false; 835 } 836 837 static QualType getCallableReturnType(const NamedDecl *ND) { 838 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 839 return FD->getReturnType(); 840 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(ND)) { 841 return MD->getReturnType(); 842 } else { 843 llvm_unreachable("Unexpected decl"); 844 } 845 } 846 847 bool RetainSummaryManager::applyParamAnnotationEffect( 848 const ParmVarDecl *pd, unsigned parm_idx, const NamedDecl *FD, 849 RetainSummaryTemplate &Template) { 850 QualType QT = pd->getType(); 851 if (auto K = 852 hasAnyEnabledAttrOf<NSConsumedAttr, CFConsumedAttr, OSConsumedAttr, 853 GeneralizedConsumedAttr>(pd, QT)) { 854 Template->addArg(AF, parm_idx, ArgEffect(DecRef, *K)); 855 return true; 856 } else if (auto K = hasAnyEnabledAttrOf< 857 CFReturnsRetainedAttr, OSReturnsRetainedAttr, 858 OSReturnsRetainedOnNonZeroAttr, OSReturnsRetainedOnZeroAttr, 859 GeneralizedReturnsRetainedAttr>(pd, QT)) { 860 861 // For OSObjects, we try to guess whether the object is created based 862 // on the return value. 863 if (K == ObjKind::OS) { 864 QualType QT = getCallableReturnType(FD); 865 866 bool HasRetainedOnZero = pd->hasAttr<OSReturnsRetainedOnZeroAttr>(); 867 bool HasRetainedOnNonZero = pd->hasAttr<OSReturnsRetainedOnNonZeroAttr>(); 868 869 // The usual convention is to create an object on non-zero return, but 870 // it's reverted if the typedef chain has a typedef kern_return_t, 871 // because kReturnSuccess constant is defined as zero. 872 // The convention can be overwritten by custom attributes. 873 bool SuccessOnZero = 874 HasRetainedOnZero || 875 (hasTypedefNamed(QT, "kern_return_t") && !HasRetainedOnNonZero); 876 bool ShouldSplit = !QT.isNull() && !QT->isVoidType(); 877 ArgEffectKind AK = RetainedOutParameter; 878 if (ShouldSplit && SuccessOnZero) { 879 AK = RetainedOutParameterOnZero; 880 } else if (ShouldSplit && (!SuccessOnZero || HasRetainedOnNonZero)) { 881 AK = RetainedOutParameterOnNonZero; 882 } 883 Template->addArg(AF, parm_idx, ArgEffect(AK, ObjKind::OS)); 884 } 885 886 // For others: 887 // Do nothing. Retained out parameters will either point to a +1 reference 888 // or NULL, but the way you check for failure differs depending on the 889 // API. Consequently, we don't have a good way to track them yet. 890 return true; 891 } else if (auto K = hasAnyEnabledAttrOf<CFReturnsNotRetainedAttr, 892 OSReturnsNotRetainedAttr, 893 GeneralizedReturnsNotRetainedAttr>( 894 pd, QT)) { 895 Template->addArg(AF, parm_idx, ArgEffect(UnretainedOutParameter, *K)); 896 return true; 897 } 898 899 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 900 for (const auto *OD : MD->overridden_methods()) { 901 const ParmVarDecl *OP = OD->parameters()[parm_idx]; 902 if (applyParamAnnotationEffect(OP, parm_idx, OD, Template)) 903 return true; 904 } 905 } 906 907 return false; 908 } 909 910 void 911 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ, 912 const FunctionDecl *FD) { 913 if (!FD) 914 return; 915 916 assert(Summ && "Must have a summary to add annotations to."); 917 RetainSummaryTemplate Template(Summ, *this); 918 919 // Effects on the parameters. 920 unsigned parm_idx = 0; 921 for (auto pi = FD->param_begin(), 922 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) 923 applyParamAnnotationEffect(*pi, parm_idx, FD, Template); 924 925 QualType RetTy = FD->getReturnType(); 926 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD)) 927 Template->setRetEffect(*RetE); 928 929 if (hasAnyEnabledAttrOf<OSConsumesThisAttr>(FD, RetTy)) 930 Template->setThisEffect(ArgEffect(DecRef, ObjKind::OS)); 931 } 932 933 void 934 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ, 935 const ObjCMethodDecl *MD) { 936 if (!MD) 937 return; 938 939 assert(Summ && "Must have a valid summary to add annotations to"); 940 RetainSummaryTemplate Template(Summ, *this); 941 942 // Effects on the receiver. 943 if (hasAnyEnabledAttrOf<NSConsumesSelfAttr>(MD, MD->getReturnType())) 944 Template->setReceiverEffect(ArgEffect(DecRef, ObjKind::ObjC)); 945 946 // Effects on the parameters. 947 unsigned parm_idx = 0; 948 for (auto pi = MD->param_begin(), pe = MD->param_end(); pi != pe; 949 ++pi, ++parm_idx) 950 applyParamAnnotationEffect(*pi, parm_idx, MD, Template); 951 952 QualType RetTy = MD->getReturnType(); 953 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD)) 954 Template->setRetEffect(*RetE); 955 } 956 957 const RetainSummary * 958 RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD, 959 Selector S, QualType RetTy) { 960 // Any special effects? 961 ArgEffect ReceiverEff = ArgEffect(DoNothing, ObjKind::ObjC); 962 RetEffect ResultEff = RetEffect::MakeNoRet(); 963 964 // Check the method family, and apply any default annotations. 965 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) { 966 case OMF_None: 967 case OMF_initialize: 968 case OMF_performSelector: 969 // Assume all Objective-C methods follow Cocoa Memory Management rules. 970 // FIXME: Does the non-threaded performSelector family really belong here? 971 // The selector could be, say, @selector(copy). 972 if (cocoa::isCocoaObjectRef(RetTy)) 973 ResultEff = RetEffect::MakeNotOwned(ObjKind::ObjC); 974 else if (coreFoundation::isCFObjectRef(RetTy)) { 975 // ObjCMethodDecl currently doesn't consider CF objects as valid return 976 // values for alloc, new, copy, or mutableCopy, so we have to 977 // double-check with the selector. This is ugly, but there aren't that 978 // many Objective-C methods that return CF objects, right? 979 if (MD) { 980 switch (S.getMethodFamily()) { 981 case OMF_alloc: 982 case OMF_new: 983 case OMF_copy: 984 case OMF_mutableCopy: 985 ResultEff = RetEffect::MakeOwned(ObjKind::CF); 986 break; 987 default: 988 ResultEff = RetEffect::MakeNotOwned(ObjKind::CF); 989 break; 990 } 991 } else { 992 ResultEff = RetEffect::MakeNotOwned(ObjKind::CF); 993 } 994 } 995 break; 996 case OMF_init: 997 ResultEff = ObjCInitRetE; 998 ReceiverEff = ArgEffect(DecRef, ObjKind::ObjC); 999 break; 1000 case OMF_alloc: 1001 case OMF_new: 1002 case OMF_copy: 1003 case OMF_mutableCopy: 1004 if (cocoa::isCocoaObjectRef(RetTy)) 1005 ResultEff = ObjCAllocRetE; 1006 else if (coreFoundation::isCFObjectRef(RetTy)) 1007 ResultEff = RetEffect::MakeOwned(ObjKind::CF); 1008 break; 1009 case OMF_autorelease: 1010 ReceiverEff = ArgEffect(Autorelease, ObjKind::ObjC); 1011 break; 1012 case OMF_retain: 1013 ReceiverEff = ArgEffect(IncRef, ObjKind::ObjC); 1014 break; 1015 case OMF_release: 1016 ReceiverEff = ArgEffect(DecRef, ObjKind::ObjC); 1017 break; 1018 case OMF_dealloc: 1019 ReceiverEff = ArgEffect(Dealloc, ObjKind::ObjC); 1020 break; 1021 case OMF_self: 1022 // -self is handled specially by the ExprEngine to propagate the receiver. 1023 break; 1024 case OMF_retainCount: 1025 case OMF_finalize: 1026 // These methods don't return objects. 1027 break; 1028 } 1029 1030 // If one of the arguments in the selector has the keyword 'delegate' we 1031 // should stop tracking the reference count for the receiver. This is 1032 // because the reference count is quite possibly handled by a delegate 1033 // method. 1034 if (S.isKeywordSelector()) { 1035 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) { 1036 StringRef Slot = S.getNameForSlot(i); 1037 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) { 1038 if (ResultEff == ObjCInitRetE) 1039 ResultEff = RetEffect::MakeNoRetHard(); 1040 else 1041 ReceiverEff = ArgEffect(StopTrackingHard, ObjKind::ObjC); 1042 } 1043 } 1044 } 1045 1046 if (ReceiverEff.getKind() == DoNothing && 1047 ResultEff.getKind() == RetEffect::NoRet) 1048 return getDefaultSummary(); 1049 1050 return getPersistentSummary(ResultEff, ArgEffects(AF.getEmptyMap()), 1051 ArgEffect(ReceiverEff), ArgEffect(MayEscape)); 1052 } 1053 1054 const RetainSummary * 1055 RetainSummaryManager::getClassMethodSummary(const ObjCMessageExpr *ME) { 1056 assert(!ME->isInstanceMessage()); 1057 const ObjCInterfaceDecl *Class = ME->getReceiverInterface(); 1058 1059 return getMethodSummary(ME->getSelector(), Class, ME->getMethodDecl(), 1060 ME->getType(), ObjCClassMethodSummaries); 1061 } 1062 1063 const RetainSummary *RetainSummaryManager::getInstanceMethodSummary( 1064 const ObjCMessageExpr *ME, 1065 QualType ReceiverType) { 1066 const ObjCInterfaceDecl *ReceiverClass = nullptr; 1067 1068 // We do better tracking of the type of the object than the core ExprEngine. 1069 // See if we have its type in our private state. 1070 if (!ReceiverType.isNull()) 1071 if (const auto *PT = ReceiverType->getAs<ObjCObjectPointerType>()) 1072 ReceiverClass = PT->getInterfaceDecl(); 1073 1074 // If we don't know what kind of object this is, fall back to its static type. 1075 if (!ReceiverClass) 1076 ReceiverClass = ME->getReceiverInterface(); 1077 1078 // FIXME: The receiver could be a reference to a class, meaning that 1079 // we should use the class method. 1080 // id x = [NSObject class]; 1081 // [x performSelector:... withObject:... afterDelay:...]; 1082 Selector S = ME->getSelector(); 1083 const ObjCMethodDecl *Method = ME->getMethodDecl(); 1084 if (!Method && ReceiverClass) 1085 Method = ReceiverClass->getInstanceMethod(S); 1086 1087 return getMethodSummary(S, ReceiverClass, Method, ME->getType(), 1088 ObjCMethodSummaries); 1089 } 1090 1091 const RetainSummary * 1092 RetainSummaryManager::getMethodSummary(Selector S, 1093 const ObjCInterfaceDecl *ID, 1094 const ObjCMethodDecl *MD, QualType RetTy, 1095 ObjCMethodSummariesTy &CachedSummaries) { 1096 1097 // Objective-C method summaries are only applicable to ObjC and CF objects. 1098 if (!TrackObjCAndCFObjects) 1099 return getDefaultSummary(); 1100 1101 // Look up a summary in our summary cache. 1102 const RetainSummary *Summ = CachedSummaries.find(ID, S); 1103 1104 if (!Summ) { 1105 Summ = getStandardMethodSummary(MD, S, RetTy); 1106 1107 // Annotations override defaults. 1108 updateSummaryFromAnnotations(Summ, MD); 1109 1110 // Memoize the summary. 1111 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ; 1112 } 1113 1114 return Summ; 1115 } 1116 1117 void RetainSummaryManager::InitializeClassMethodSummaries() { 1118 ArgEffects ScratchArgs = AF.getEmptyMap(); 1119 1120 // Create the [NSAssertionHandler currentHander] summary. 1121 addClassMethSummary("NSAssertionHandler", "currentHandler", 1122 getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::ObjC), 1123 ScratchArgs)); 1124 1125 // Create the [NSAutoreleasePool addObject:] summary. 1126 ScratchArgs = AF.add(ScratchArgs, 0, ArgEffect(Autorelease)); 1127 addClassMethSummary("NSAutoreleasePool", "addObject", 1128 getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs, 1129 ArgEffect(DoNothing), 1130 ArgEffect(Autorelease))); 1131 } 1132 1133 void RetainSummaryManager::InitializeMethodSummaries() { 1134 1135 ArgEffects ScratchArgs = AF.getEmptyMap(); 1136 // Create the "init" selector. It just acts as a pass-through for the 1137 // receiver. 1138 const RetainSummary *InitSumm = getPersistentSummary( 1139 ObjCInitRetE, ScratchArgs, ArgEffect(DecRef, ObjKind::ObjC)); 1140 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm); 1141 1142 // awakeAfterUsingCoder: behaves basically like an 'init' method. It 1143 // claims the receiver and returns a retained object. 1144 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx), 1145 InitSumm); 1146 1147 // The next methods are allocators. 1148 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE, 1149 ScratchArgs); 1150 const RetainSummary *CFAllocSumm = 1151 getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs); 1152 1153 // Create the "retain" selector. 1154 RetEffect NoRet = RetEffect::MakeNoRet(); 1155 const RetainSummary *Summ = getPersistentSummary( 1156 NoRet, ScratchArgs, ArgEffect(IncRef, ObjKind::ObjC)); 1157 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ); 1158 1159 // Create the "release" selector. 1160 Summ = getPersistentSummary(NoRet, ScratchArgs, 1161 ArgEffect(DecRef, ObjKind::ObjC)); 1162 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ); 1163 1164 // Create the -dealloc summary. 1165 Summ = getPersistentSummary(NoRet, ScratchArgs, ArgEffect(Dealloc, 1166 ObjKind::ObjC)); 1167 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ); 1168 1169 // Create the "autorelease" selector. 1170 Summ = getPersistentSummary(NoRet, ScratchArgs, ArgEffect(Autorelease, 1171 ObjKind::ObjC)); 1172 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ); 1173 1174 // For NSWindow, allocated objects are (initially) self-owned. 1175 // FIXME: For now we opt for false negatives with NSWindow, as these objects 1176 // self-own themselves. However, they only do this once they are displayed. 1177 // Thus, we need to track an NSWindow's display status. 1178 // This is tracked in <rdar://problem/6062711>. 1179 // See also http://llvm.org/bugs/show_bug.cgi?id=3714. 1180 const RetainSummary *NoTrackYet = 1181 getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs, 1182 ArgEffect(StopTracking), ArgEffect(StopTracking)); 1183 1184 addClassMethSummary("NSWindow", "alloc", NoTrackYet); 1185 1186 // For NSPanel (which subclasses NSWindow), allocated objects are not 1187 // self-owned. 1188 // FIXME: For now we don't track NSPanels. object for the same reason 1189 // as for NSWindow objects. 1190 addClassMethSummary("NSPanel", "alloc", NoTrackYet); 1191 1192 // For NSNull, objects returned by +null are singletons that ignore 1193 // retain/release semantics. Just don't track them. 1194 // <rdar://problem/12858915> 1195 addClassMethSummary("NSNull", "null", NoTrackYet); 1196 1197 // Don't track allocated autorelease pools, as it is okay to prematurely 1198 // exit a method. 1199 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet); 1200 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false); 1201 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet); 1202 1203 // Create summaries QCRenderer/QCView -createSnapShotImageOfType: 1204 addInstMethSummary("QCRenderer", AllocSumm, "createSnapshotImageOfType"); 1205 addInstMethSummary("QCView", AllocSumm, "createSnapshotImageOfType"); 1206 1207 // Create summaries for CIContext, 'createCGImage' and 1208 // 'createCGLayerWithSize'. These objects are CF objects, and are not 1209 // automatically garbage collected. 1210 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect"); 1211 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect", 1212 "format", "colorSpace"); 1213 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info"); 1214 } 1215 1216 const RetainSummary * 1217 RetainSummaryManager::getMethodSummary(const ObjCMethodDecl *MD) { 1218 const ObjCInterfaceDecl *ID = MD->getClassInterface(); 1219 Selector S = MD->getSelector(); 1220 QualType ResultTy = MD->getReturnType(); 1221 1222 ObjCMethodSummariesTy *CachedSummaries; 1223 if (MD->isInstanceMethod()) 1224 CachedSummaries = &ObjCMethodSummaries; 1225 else 1226 CachedSummaries = &ObjCClassMethodSummaries; 1227 1228 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries); 1229 } 1230