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