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