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/RetainSummaryManager.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/ASTMatchers/ASTMatchFinder.h"
20 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21 #include <optional>
22
23 using namespace clang;
24 using namespace ento;
25
26 template <class T>
isOneOf()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>
isOneOf()34 constexpr static bool isOneOf() {
35 return std::is_same_v<T, P> || isOneOf<T, ToCompare...>();
36 }
37
38 namespace {
39
40 /// Fake attribute class for RC* attributes.
41 struct GeneralizedReturnsRetainedAttr {
classof__anon45cc3d790111::GeneralizedReturnsRetainedAttr42 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 {
classof__anon45cc3d790111::GeneralizedReturnsNotRetainedAttr50 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 {
classof__anon45cc3d790111::GeneralizedConsumedAttr58 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>
hasAnyEnabledAttrOf(const Decl * D,QualType QT)68 std::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 std::nullopt;
75
76 K = ObjKind::CF;
77 } else if (isOneOf<T, NSConsumedAttr, NSConsumesSelfAttr,
78 NSReturnsAutoreleasedAttr, NSReturnsRetainedAttr,
79 NSReturnsNotRetainedAttr, NSConsumesSelfAttr>()) {
80
81 if (!TrackObjCAndCFObjects)
82 return std::nullopt;
83
84 if (isOneOf<T, NSReturnsRetainedAttr, NSReturnsAutoreleasedAttr,
85 NSReturnsNotRetainedAttr>() &&
86 !cocoa::isCocoaObjectRef(QT))
87 return std::nullopt;
88 K = ObjKind::ObjC;
89 } else if (isOneOf<T, OSConsumedAttr, OSConsumesThisAttr,
90 OSReturnsNotRetainedAttr, OSReturnsRetainedAttr,
91 OSReturnsRetainedOnZeroAttr,
92 OSReturnsRetainedOnNonZeroAttr>()) {
93 if (!TrackOSObjects)
94 return std::nullopt;
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 std::nullopt;
106 }
107
108 template <class T1, class T2, class... Others>
hasAnyEnabledAttrOf(const Decl * D,QualType QT)109 std::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 *
getPersistentSummary(const RetainSummary & OldSumm)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
isSubclass(const Decl * D,StringRef ClassName)140 static bool isSubclass(const Decl *D,
141 StringRef ClassName) {
142 using namespace ast_matchers;
143 DeclarationMatcher SubclassM =
144 cxxRecordDecl(isSameOrDerivedFrom(std::string(ClassName)));
145 return !(match(SubclassM, *D, D->getASTContext()).empty());
146 }
147
isExactClass(const Decl * D,StringRef ClassName)148 static bool isExactClass(const Decl *D, StringRef ClassName) {
149 using namespace ast_matchers;
150 DeclarationMatcher sameClassM =
151 cxxRecordDecl(hasName(std::string(ClassName)));
152 return !(match(sameClassM, *D, D->getASTContext()).empty());
153 }
154
isOSObjectSubclass(const Decl * D)155 static bool isOSObjectSubclass(const Decl *D) {
156 return D && isSubclass(D, "OSMetaClassBase") &&
157 !isExactClass(D, "OSMetaClass");
158 }
159
isOSObjectDynamicCast(StringRef S)160 static bool isOSObjectDynamicCast(StringRef S) { return S == "safeMetaCast"; }
161
isOSObjectRequiredCast(StringRef S)162 static bool isOSObjectRequiredCast(StringRef S) {
163 return S == "requiredMetaCast";
164 }
165
isOSObjectThisCast(StringRef S)166 static bool isOSObjectThisCast(StringRef S) {
167 return S == "metaCast";
168 }
169
170
isOSObjectPtr(QualType QT)171 static bool isOSObjectPtr(QualType QT) {
172 return isOSObjectSubclass(QT->getPointeeCXXRecordDecl());
173 }
174
isISLObjectRef(QualType Ty)175 static bool isISLObjectRef(QualType Ty) {
176 return StringRef(Ty.getAsString()).starts_with("isl_");
177 }
178
isOSIteratorSubclass(const Decl * D)179 static bool isOSIteratorSubclass(const Decl *D) {
180 return isSubclass(D, "OSIterator");
181 }
182
hasRCAnnotation(const Decl * D,StringRef rcAnnotation)183 static bool hasRCAnnotation(const Decl *D, StringRef rcAnnotation) {
184 for (const auto *Ann : D->specific_attrs<AnnotateAttr>()) {
185 if (Ann->getAnnotation() == rcAnnotation)
186 return true;
187 }
188 return false;
189 }
190
isRetain(const FunctionDecl * FD,StringRef FName)191 static bool isRetain(const FunctionDecl *FD, StringRef FName) {
192 return FName.starts_with_insensitive("retain") ||
193 FName.ends_with_insensitive("retain");
194 }
195
isRelease(const FunctionDecl * FD,StringRef FName)196 static bool isRelease(const FunctionDecl *FD, StringRef FName) {
197 return FName.starts_with_insensitive("release") ||
198 FName.ends_with_insensitive("release");
199 }
200
isAutorelease(const FunctionDecl * FD,StringRef FName)201 static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
202 return FName.starts_with_insensitive("autorelease") ||
203 FName.ends_with_insensitive("autorelease");
204 }
205
isMakeCollectable(StringRef FName)206 static bool isMakeCollectable(StringRef FName) {
207 return FName.contains_insensitive("MakeCollectable");
208 }
209
210 /// A function is OSObject related if it is declared on a subclass
211 /// of OSObject, or any of the parameters is a subclass of an OSObject.
isOSObjectRelated(const CXXMethodDecl * MD)212 static bool isOSObjectRelated(const CXXMethodDecl *MD) {
213 if (isOSObjectSubclass(MD->getParent()))
214 return true;
215
216 for (ParmVarDecl *Param : MD->parameters()) {
217 QualType PT = Param->getType()->getPointeeType();
218 if (!PT.isNull())
219 if (CXXRecordDecl *RD = PT->getAsCXXRecordDecl())
220 if (isOSObjectSubclass(RD))
221 return true;
222 }
223
224 return false;
225 }
226
227 bool
isKnownSmartPointer(QualType QT)228 RetainSummaryManager::isKnownSmartPointer(QualType QT) {
229 QT = QT.getCanonicalType();
230 const auto *RD = QT->getAsCXXRecordDecl();
231 if (!RD)
232 return false;
233 const IdentifierInfo *II = RD->getIdentifier();
234 if (II && II->getName() == "smart_ptr")
235 if (const auto *ND = dyn_cast<NamespaceDecl>(RD->getDeclContext()))
236 if (ND->getNameAsString() == "os")
237 return true;
238 return false;
239 }
240
241 const RetainSummary *
getSummaryForOSObject(const FunctionDecl * FD,StringRef FName,QualType RetTy)242 RetainSummaryManager::getSummaryForOSObject(const FunctionDecl *FD,
243 StringRef FName, QualType RetTy) {
244 assert(TrackOSObjects &&
245 "Requesting a summary for an OSObject but OSObjects are not tracked");
246
247 if (RetTy->isPointerType()) {
248 const CXXRecordDecl *PD = RetTy->getPointeeType()->getAsCXXRecordDecl();
249 if (PD && isOSObjectSubclass(PD)) {
250 if (isOSObjectDynamicCast(FName) || isOSObjectRequiredCast(FName) ||
251 isOSObjectThisCast(FName))
252 return getDefaultSummary();
253
254 // TODO: Add support for the slightly common *Matching(table) idiom.
255 // Cf. IOService::nameMatching() etc. - these function have an unusual
256 // contract of returning at +0 or +1 depending on their last argument.
257 if (FName.ends_with("Matching")) {
258 return getPersistentStopSummary();
259 }
260
261 // All objects returned with functions *not* starting with 'get',
262 // or iterators, are returned at +1.
263 if ((!FName.starts_with("get") && !FName.starts_with("Get")) ||
264 isOSIteratorSubclass(PD)) {
265 return getOSSummaryCreateRule(FD);
266 } else {
267 return getOSSummaryGetRule(FD);
268 }
269 }
270 }
271
272 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
273 const CXXRecordDecl *Parent = MD->getParent();
274 if (Parent && isOSObjectSubclass(Parent)) {
275 if (FName == "release" || FName == "taggedRelease")
276 return getOSSummaryReleaseRule(FD);
277
278 if (FName == "retain" || FName == "taggedRetain")
279 return getOSSummaryRetainRule(FD);
280
281 if (FName == "free")
282 return getOSSummaryFreeRule(FD);
283
284 if (MD->getOverloadedOperator() == OO_New)
285 return getOSSummaryCreateRule(MD);
286 }
287 }
288
289 return nullptr;
290 }
291
getSummaryForObjCOrCFObject(const FunctionDecl * FD,StringRef FName,QualType RetTy,const FunctionType * FT,bool & AllowAnnotations)292 const RetainSummary *RetainSummaryManager::getSummaryForObjCOrCFObject(
293 const FunctionDecl *FD,
294 StringRef FName,
295 QualType RetTy,
296 const FunctionType *FT,
297 bool &AllowAnnotations) {
298
299 ArgEffects ScratchArgs(AF.getEmptyMap());
300
301 std::string RetTyName = RetTy.getAsString();
302 if (FName == "pthread_create" || FName == "pthread_setspecific") {
303 // It's not uncommon to pass a tracked object into the thread
304 // as 'void *arg', and then release it inside the thread.
305 // FIXME: We could build a much more precise model for these functions.
306 return getPersistentStopSummary();
307 } else if(FName == "NSMakeCollectable") {
308 // Handle: id NSMakeCollectable(CFTypeRef)
309 AllowAnnotations = false;
310 return RetTy->isObjCIdType() ? getUnarySummary(FT, DoNothing)
311 : getPersistentStopSummary();
312 } else if (FName == "CMBufferQueueDequeueAndRetain" ||
313 FName == "CMBufferQueueDequeueIfDataReadyAndRetain") {
314 // These API functions are known to NOT act as a CFRetain wrapper.
315 // They simply make a new object owned by the caller.
316 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF),
317 ScratchArgs,
318 ArgEffect(DoNothing),
319 ArgEffect(DoNothing));
320 } else if (FName == "CFPlugInInstanceCreate") {
321 return getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs);
322 } else if (FName == "IORegistryEntrySearchCFProperty" ||
323 (RetTyName == "CFMutableDictionaryRef" &&
324 (FName == "IOBSDNameMatching" || FName == "IOServiceMatching" ||
325 FName == "IOServiceNameMatching" ||
326 FName == "IORegistryEntryIDMatching" ||
327 FName == "IOOpenFirmwarePathMatching"))) {
328 // Yes, these IOKit functions return CF objects.
329 // They also violate the CF naming convention.
330 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs,
331 ArgEffect(DoNothing), ArgEffect(DoNothing));
332 } else if (FName == "IOServiceGetMatchingService" ||
333 FName == "IOServiceGetMatchingServices") {
334 // These IOKit functions accept CF objects as arguments.
335 // They also consume them without an appropriate annotation.
336 ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(DecRef, ObjKind::CF));
337 return getPersistentSummary(RetEffect::MakeNoRet(),
338 ScratchArgs,
339 ArgEffect(DoNothing), ArgEffect(DoNothing));
340 } else if (FName == "IOServiceAddNotification" ||
341 FName == "IOServiceAddMatchingNotification") {
342 // More IOKit functions suddenly accepting (and even more suddenly,
343 // consuming) CF objects.
344 ScratchArgs = AF.add(ScratchArgs, 2, ArgEffect(DecRef, ObjKind::CF));
345 return getPersistentSummary(RetEffect::MakeNoRet(),
346 ScratchArgs,
347 ArgEffect(DoNothing), ArgEffect(DoNothing));
348 } else if (FName == "CVPixelBufferCreateWithBytes") {
349 // Eventually this can be improved by recognizing that the pixel
350 // buffer passed to CVPixelBufferCreateWithBytes is released via
351 // a callback and doing full IPA to make sure this is done correctly.
352 // Note that it's passed as a 'void *', so it's hard to annotate.
353 // FIXME: This function also has an out parameter that returns an
354 // allocated object.
355 ScratchArgs = AF.add(ScratchArgs, 7, ArgEffect(StopTracking));
356 return getPersistentSummary(RetEffect::MakeNoRet(),
357 ScratchArgs,
358 ArgEffect(DoNothing), ArgEffect(DoNothing));
359 } else if (FName == "CGBitmapContextCreateWithData") {
360 // This is similar to the CVPixelBufferCreateWithBytes situation above.
361 // Eventually this can be improved by recognizing that 'releaseInfo'
362 // passed to CGBitmapContextCreateWithData is released via
363 // a callback and doing full IPA to make sure this is done correctly.
364 ScratchArgs = AF.add(ScratchArgs, 8, ArgEffect(ArgEffect(StopTracking)));
365 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs,
366 ArgEffect(DoNothing), ArgEffect(DoNothing));
367 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
368 // Same as CVPixelBufferCreateWithBytes, just more arguments.
369 ScratchArgs = AF.add(ScratchArgs, 12, ArgEffect(StopTracking));
370 return getPersistentSummary(RetEffect::MakeNoRet(),
371 ScratchArgs,
372 ArgEffect(DoNothing), ArgEffect(DoNothing));
373 } else if (FName == "VTCompressionSessionEncodeFrame" ||
374 FName == "VTCompressionSessionEncodeMultiImageFrame") {
375 // The context argument passed to VTCompressionSessionEncodeFrame() et.al.
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.starts_with("NSLog")) {
395 return getDoNothingSummary();
396 } else if (FName.starts_with("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.starts_with("CG") || FName.starts_with("CF")) {
456 // Test for 'CGCF'.
457 FName = FName.substr(FName.starts_with("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 *
generateSummary(const FunctionDecl * FD,bool & AllowAnnotations)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 *
getFunctionSummary(const FunctionDecl * FD)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
getStopTrackingHardEquivalent(ArgEffect E)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 *
updateSummaryForNonZeroCallbackArg(const RetainSummary * S,AnyCall & C)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
updateSummaryForReceiverUnconsumedSelf(const RetainSummary * & S)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
updateSummaryForArgumentTypes(const AnyCall & C,const RetainSummary * & RS)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 *
getSummary(AnyCall C,bool HasNonZeroCallbackArg,bool IsReceiverUnconsumedSelf,QualType ReceiverType)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 *
getCFCreateGetRuleSummary(const FunctionDecl * FD)705 RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
706 if (coreFoundation::followsCreateRule(FD))
707 return getCFSummaryCreateRule(FD);
708
709 return getCFSummaryGetRule(FD);
710 }
711
isTrustedReferenceCountImplementation(const Decl * FD)712 bool RetainSummaryManager::isTrustedReferenceCountImplementation(
713 const Decl *FD) {
714 return hasRCAnnotation(FD, "rc_ownership_trusted_implementation");
715 }
716
717 std::optional<RetainSummaryManager::BehaviorSummary>
canEval(const CallExpr * CE,const FunctionDecl * FD,bool & hasTrustedImplementationAnnotation)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 *
getUnarySummary(const FunctionType * FT,ArgEffectKind AE)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 *
getOSSummaryRetainRule(const FunctionDecl * FD)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 *
getOSSummaryReleaseRule(const FunctionDecl * FD)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 *
getOSSummaryFreeRule(const FunctionDecl * FD)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 *
getOSSummaryCreateRule(const FunctionDecl * FD)832 RetainSummaryManager::getOSSummaryCreateRule(const FunctionDecl *FD) {
833 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::OS),
834 AF.getEmptyMap());
835 }
836
837 const RetainSummary *
getOSSummaryGetRule(const FunctionDecl * FD)838 RetainSummaryManager::getOSSummaryGetRule(const FunctionDecl *FD) {
839 return getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::OS),
840 AF.getEmptyMap());
841 }
842
843 const RetainSummary *
getCFSummaryCreateRule(const FunctionDecl * FD)844 RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
845 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF),
846 ArgEffects(AF.getEmptyMap()));
847 }
848
849 const RetainSummary *
getCFSummaryGetRule(const FunctionDecl * FD)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>
getRetEffectFromAnnotations(QualType RetTy,const Decl * D)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.
hasTypedefNamed(QualType QT,StringRef 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
getCallableReturnType(const NamedDecl * ND)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
applyParamAnnotationEffect(const ParmVarDecl * pd,unsigned parm_idx,const NamedDecl * FD,RetainSummaryTemplate & Template)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
updateSummaryFromAnnotations(const RetainSummary * & Summ,const FunctionDecl * FD)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
updateSummaryFromAnnotations(const RetainSummary * & Summ,const ObjCMethodDecl * MD)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 *
getStandardMethodSummary(const ObjCMethodDecl * MD,Selector S,QualType RetTy)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.ends_with_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 *
getClassMethodSummary(const ObjCMessageExpr * ME)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
getInstanceMethodSummary(const ObjCMessageExpr * ME,QualType ReceiverType)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 *
getMethodSummary(Selector S,const ObjCInterfaceDecl * ID,const ObjCMethodDecl * MD,QualType RetTy,ObjCMethodSummariesTy & CachedSummaries)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
InitializeClassMethodSummaries()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
InitializeMethodSummaries()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 *
getMethodSummary(const ObjCMethodDecl * MD)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