clang 22.0.0git
RetainSummaryManager.cpp
Go to the documentation of this file.
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
16#include "clang/AST/Attr.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.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>(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>(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>(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>() &&
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>()) {
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, 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
140static 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
148static bool isExactClass(const Decl *D, StringRef ClassName) {
149 using namespace ast_matchers;
150 DeclarationMatcher sameClassM = cxxRecordDecl(hasName(ClassName));
151 return !(match(sameClassM, *D, D->getASTContext()).empty());
152}
153
154static bool isOSObjectSubclass(const Decl *D) {
155 return D && isSubclass(D, "OSMetaClassBase") &&
156 !isExactClass(D, "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) {
172}
173
174static bool isISLObjectRef(QualType Ty) {
175 return StringRef(Ty.getAsString()).starts_with("isl_");
176}
177
178static bool isOSIteratorSubclass(const Decl *D) {
179 return isSubclass(D, "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("retain") ||
192 FName.ends_with_insensitive("retain");
193}
194
195static bool isRelease(const FunctionDecl *FD, StringRef FName) {
196 return FName.starts_with_insensitive("release") ||
197 FName.ends_with_insensitive("release");
198}
199
200static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
201 return FName.starts_with_insensitive("autorelease") ||
202 FName.ends_with_insensitive("autorelease");
203}
204
205static bool isMakeCollectable(StringRef FName) {
206 return FName.contains_insensitive("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(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(RD))
220 return true;
221 }
222
223 return false;
224}
225
226bool
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>(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(PD)) {
249 if (isOSObjectDynamicCast(FName) || isOSObjectRequiredCast(FName) ||
250 isOSObjectThisCast(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("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("get") && !FName.starts_with("Get")) ||
264 return getOSSummaryCreateRule(FD);
265 } else {
266 return getOSSummaryGetRule(FD);
267 }
268 }
269 }
270
271 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
272 const CXXRecordDecl *Parent = MD->getParent();
273 if (Parent && isOSObjectSubclass(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(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, 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(RetEffect::MakeOwned(ObjKind::CF),
316 ScratchArgs,
317 ArgEffect(DoNothing),
318 ArgEffect(DoNothing));
319 } else if (FName == "CFPlugInInstanceCreate") {
320 return getPersistentSummary(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(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs,
330 ArgEffect(DoNothing), 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(ScratchArgs, 1, ArgEffect(DecRef, ObjKind::CF));
336 return getPersistentSummary(RetEffect::MakeNoRet(),
337 ScratchArgs,
338 ArgEffect(DoNothing), 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(ScratchArgs, 2, ArgEffect(DecRef, ObjKind::CF));
344 return getPersistentSummary(RetEffect::MakeNoRet(),
345 ScratchArgs,
346 ArgEffect(DoNothing), 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(ScratchArgs, 7, ArgEffect(StopTracking));
355 return getPersistentSummary(RetEffect::MakeNoRet(),
356 ScratchArgs,
357 ArgEffect(DoNothing), 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(ScratchArgs, 8, ArgEffect(ArgEffect(StopTracking)));
364 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs,
365 ArgEffect(DoNothing), ArgEffect(DoNothing));
366 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
367 // Same as CVPixelBufferCreateWithBytes, just more arguments.
368 ScratchArgs = AF.add(ScratchArgs, 12, ArgEffect(StopTracking));
369 return getPersistentSummary(RetEffect::MakeNoRet(),
370 ScratchArgs,
371 ArgEffect(DoNothing), 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(ScratchArgs, 5, ArgEffect(StopTracking));
380 return getPersistentSummary(RetEffect::MakeNoRet(),
381 ScratchArgs,
382 ArgEffect(DoNothing), 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(ScratchArgs, 1, ArgEffect(StopTracking));
390 return getPersistentSummary(RetEffect::MakeNoRet(),
391 ScratchArgs,
392 ArgEffect(DoNothing), ArgEffect(DoNothing));
393 } else if (FName.starts_with("NSLog")) {
394 return getDoNothingSummary();
395 } else if (FName.starts_with("NS") && FName.contains("Insert")) {
396 // Allowlist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
397 // be deallocated by NSMapRemove.
398 ScratchArgs = AF.add(ScratchArgs, 1, ArgEffect(StopTracking));
399 ScratchArgs = AF.add(ScratchArgs, 2, ArgEffect(StopTracking));
400 return getPersistentSummary(RetEffect::MakeNoRet(),
401 ScratchArgs, ArgEffect(DoNothing),
402 ArgEffect(DoNothing));
403 }
404
405 if (RetTy->isPointerType()) {
406
407 // For CoreFoundation ('CF') types.
408 if (cocoa::isRefType(RetTy, "CF", 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, 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, Autorelease);
423 } else if (isMakeCollectable(FName)) {
424 AllowAnnotations = false;
425 return getUnarySummary(FT, DoNothing);
426 } else {
427 return getCFCreateGetRuleSummary(FD);
428 }
429 }
430
431 // For CoreGraphics ('CG') and CoreVideo ('CV') types.
432 if (cocoa::isRefType(RetTy, "CG", FName) ||
433 cocoa::isRefType(RetTy, "CV", FName)) {
434 if (isRetain(FD, FName))
435 return getUnarySummary(FT, 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.
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("CG") || FName.starts_with("CF")) {
455 // Test for 'CGCF'.
456 FName = FName.substr(FName.starts_with("CGCF") ? 4 : 2);
457
458 if (isRelease(FD, FName))
459 return getUnarySummary(FT, 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("InsertValue") ||
478 FName.contains_insensitive("AddValue") ||
479 FName.contains_insensitive("SetValue") ||
480 FName.contains_insensitive("AppendValue") ||
481 FName.contains_insensitive("SetAttribute"))
482 ? MayEscape
483 : DoNothing;
484
485 return getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
486 ArgEffect(DoNothing), 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(FName.find_first_not_of('_'));
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>(FD))
517 if (!isOSObjectRelated(MD))
518 return getPersistentSummary(RetEffect::MakeNoRet(),
519 ArgEffects(AF.getEmptyMap()),
520 ArgEffect(DoNothing),
521 ArgEffect(StopTracking),
522 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(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(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
560 switch (E.getKind()) {
561 case DoNothing:
562 case Autorelease:
564 case IncRef:
569 case MayEscape:
570 case StopTracking:
571 case StopTrackingHard:
572 return E.withKind(StopTrackingHard);
573 case DecRef:
576 case Dealloc:
577 return E.withKind(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(S->getReceiverEffect());
587 ArgEffect DefEffect = getStopTrackingHardEquivalent(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(I->second);
595 if (Translated.getKind() != DefEffect.getKind())
596 ScratchArgs = AF.add(ScratchArgs, I->first, 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("CGBitmapContextCreateWithData") ||
610 Name->isStr("dispatch_data_create"))
611 RE = S->getRetEffect();
612 }
613
614 return getPersistentSummary(RE, ScratchArgs, RecEffect, DefEffect);
615}
616
617void RetainSummaryManager::updateSummaryForReceiverUnconsumedSelf(
618 const RetainSummary *&S) {
619
621
622 Template->setReceiverEffect(ArgEffect(DoNothing));
623 Template->setRetEffect(RetEffect::MakeNoRet());
624}
625
626
627void RetainSummaryManager::updateSummaryForArgumentTypes(
628 const AnyCall &C, const RetainSummary *&RS) {
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(parm_idx))
638 continue;
639
641
642 if (isISLObjectRef(QT)) {
644 } else if (isOSObjectPtr(QT)) {
645 K = ObjKind::OS;
646 } else if (cocoa::isCocoaObjectRef(QT)) {
647 K = ObjKind::ObjC;
648 } else if (coreFoundation::isCFObjectRef(QT)) {
649 K = ObjKind::CF;
650 }
651
652 if (K != ObjKind::AnyObj)
653 Template->addArg(AF, parm_idx,
654 ArgEffect(RS->getDefaultArgEffect().getKind(), K));
655 }
656}
657
658const RetainSummary *
660 bool HasNonZeroCallbackArg,
661 bool IsReceiverUnconsumedSelf,
662 QualType ReceiverType) {
663 const RetainSummary *Summ;
664 switch (C.getKind()) {
670 Summ = getFunctionSummary(cast_or_null<FunctionDecl>(C.getDecl()));
671 break;
672 case AnyCall::Block:
674 // FIXME: These calls are currently unsupported.
675 return getPersistentStopSummary();
676 case AnyCall::ObjCMethod: {
677 const auto *ME = cast_or_null<ObjCMessageExpr>(C.getExpr());
678 if (!ME) {
679 Summ = getMethodSummary(cast<ObjCMethodDecl>(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(Summ, C);
691
692 if (IsReceiverUnconsumedSelf)
693 updateSummaryForReceiverUnconsumedSelf(Summ);
694
695 updateSummaryForArgumentTypes(C, Summ);
696
697 assert(Summ && "Unknown call type?");
698 return Summ;
699}
700
701
702const RetainSummary *
703RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
705 return getCFSummaryCreateRule(FD);
706
707 return getCFSummaryGetRule(FD);
708}
709
711 const Decl *FD) {
712 return hasRCAnnotation(FD, "rc_ownership_trusted_implementation");
713}
714
715std::optional<RetainSummaryManager::BehaviorSummary>
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(FName.find_first_not_of('_'));
725
726 QualType ResultTy = CE->getCallReturnType(Ctx);
727 if (ResultTy->isObjCIdType()) {
728 if (II->isStr("NSMakeCollectable"))
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(ResultTy, "CF", FName) ||
742 cocoa::isRefType(ResultTy, "CG", FName) ||
743 cocoa::isRefType(ResultTy, "CV", FName)) &&
744 (isRetain(FD, FName) || isAutorelease(FD, FName) ||
745 isMakeCollectable(FName)))
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(FName) && FD->param_size() >= 1) {
756 } else if (isOSObjectRequiredCast(FName) && FD->param_size() >= 1) {
758 } else if (isOSObjectThisCast(FName) && isa<CXXMethodDecl>(FD) &&
759 !cast<CXXMethodDecl>(FD)->isStatic()) {
761 }
762 }
763
764 const FunctionDecl* FDD = FD->getDefinition();
766 hasTrustedImplementationAnnotation = true;
768 }
769 }
770
771 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
772 const CXXRecordDecl *Parent = MD->getParent();
773 if (TrackOSObjects && Parent && isOSObjectSubclass(Parent))
774 if (FName == "release" || FName == "retain")
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>(FT);
791 if (!FTP || FTP->getNumParams() != 1)
792 return getPersistentStopSummary();
793
794 ArgEffect Effect(AE, ObjKind::CF);
795
796 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
797 return getPersistentSummary(RetEffect::MakeNoRet(),
798 ScratchArgs,
800}
801
802const RetainSummary *
803RetainSummaryManager::getOSSummaryRetainRule(const FunctionDecl *FD) {
804 return getPersistentSummary(RetEffect::MakeNoRet(),
805 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(RetEffect::MakeNoRet(),
814 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(RetEffect::MakeNoRet(),
823 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(RetEffect::MakeOwned(ObjKind::OS),
832 AF.getEmptyMap());
833}
834
835const RetainSummary *
836RetainSummaryManager::getOSSummaryGetRule(const FunctionDecl *FD) {
837 return getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::OS),
838 AF.getEmptyMap());
839}
840
841const RetainSummary *
842RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
843 return getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF),
844 ArgEffects(AF.getEmptyMap()));
845}
846
847const RetainSummary *
848RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
849 return getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::CF),
850 ArgEffects(AF.getEmptyMap()),
851 ArgEffect(DoNothing), 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, RetTy))
865 return ObjCAllocRetE;
866
867 if (auto K = hasAnyEnabledAttrOf<CFReturnsRetainedAttr, OSReturnsRetainedAttr,
868 GeneralizedReturnsRetainedAttr>(D, RetTy))
869 return RetEffect::MakeOwned(*K);
870
871 if (auto K = hasAnyEnabledAttrOf<
872 CFReturnsNotRetainedAttr, OSReturnsNotRetainedAttr,
873 GeneralizedReturnsNotRetainedAttr, NSReturnsNotRetainedAttr,
874 NSReturnsAutoreleasedAttr>(D, RetTy))
875 return RetEffect::MakeNotOwned(*K);
876
877 if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
878 for (const auto *PD : MD->overridden_methods())
879 if (auto RE = getRetEffectFromAnnotations(RetTy, 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.
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
899 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
900 return FD->getReturnType();
901 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(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,
911 QualType QT = pd->getType();
912 if (auto K =
913 hasAnyEnabledAttrOf<NSConsumedAttr, CFConsumedAttr, OSConsumedAttr,
914 GeneralizedConsumedAttr>(pd, QT)) {
915 Template->addArg(AF, parm_idx, ArgEffect(DecRef, *K));
916 return true;
917 } else if (auto K = hasAnyEnabledAttrOf<
918 CFReturnsRetainedAttr, OSReturnsRetainedAttr,
919 OSReturnsRetainedOnNonZeroAttr, OSReturnsRetainedOnZeroAttr,
920 GeneralizedReturnsRetainedAttr>(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(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, "kern_return_t") && !HasRetainedOnNonZero);
937 bool ShouldSplit = !QT.isNull() && !QT->isVoidType();
939 if (ShouldSplit && SuccessOnZero) {
941 } else if (ShouldSplit && (!SuccessOnZero || HasRetainedOnNonZero)) {
943 }
944 Template->addArg(AF, parm_idx, 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 pd, QT)) {
956 Template->addArg(AF, parm_idx, ArgEffect(UnretainedOutParameter, *K));
957 return true;
958 }
959
960 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
961 for (const auto *OD : MD->overridden_methods()) {
962 const ParmVarDecl *OP = OD->parameters()[parm_idx];
963 if (applyParamAnnotationEffect(OP, parm_idx, 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(*pi, parm_idx, FD, Template);
985
986 QualType RetTy = FD->getReturnType();
987 if (std::optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
988 Template->setRetEffect(*RetE);
989
990 if (hasAnyEnabledAttrOf<OSConsumesThisAttr>(FD, 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>(MD, 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(*pi, parm_idx, MD, Template);
1012
1013 QualType RetTy = MD->getReturnType();
1014 if (std::optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, 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:
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(RetTy))
1035 else if (coreFoundation::isCFObjectRef(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(ObjKind::CF);
1047 break;
1048 default:
1050 break;
1051 }
1052 } else {
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(RetTy))
1066 ResultEff = ObjCAllocRetE;
1067 else if (coreFoundation::isCFObjectRef(RetTy))
1068 ResultEff = RetEffect::MakeOwned(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(i);
1098 if (Slot.ends_with_insensitive("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(ResultEff, ArgEffects(AF.getEmptyMap()),
1112 ArgEffect(ReceiverEff), 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(ME->getSelector(), Class, ME->getMethodDecl(),
1121 ME->getType(), 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(S);
1147
1148 return getMethodSummary(S, ReceiverClass, Method, ME->getType(),
1149 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(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("NSAssertionHandler", "currentHandler",
1183 getPersistentSummary(RetEffect::MakeNotOwned(ObjKind::ObjC),
1184 ScratchArgs));
1185
1186 // Create the [NSAutoreleasePool addObject:] summary.
1187 ScratchArgs = AF.add(ScratchArgs, 0, ArgEffect(Autorelease));
1188 addClassMethSummary("NSAutoreleasePool", "addObject",
1189 getPersistentSummary(RetEffect::MakeNoRet(), ScratchArgs,
1190 ArgEffect(DoNothing),
1191 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 ObjCInitRetE, ScratchArgs, ArgEffect(DecRef, ObjKind::ObjC));
1201 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1202
1203 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1204 // claims the receiver and returns a retained object.
1205 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1206 InitSumm);
1207
1208 // The next methods are allocators.
1209 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE,
1210 ScratchArgs);
1211 const RetainSummary *CFAllocSumm =
1212 getPersistentSummary(RetEffect::MakeOwned(ObjKind::CF), ScratchArgs);
1213
1214 // Create the "retain" selector.
1215 RetEffect NoRet = RetEffect::MakeNoRet();
1216 const RetainSummary *Summ = getPersistentSummary(
1217 NoRet, ScratchArgs, ArgEffect(IncRef, ObjKind::ObjC));
1218 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
1219
1220 // Create the "release" selector.
1221 Summ = getPersistentSummary(NoRet, ScratchArgs,
1222 ArgEffect(DecRef, ObjKind::ObjC));
1223 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
1224
1225 // Create the -dealloc summary.
1226 Summ = getPersistentSummary(NoRet, ScratchArgs, ArgEffect(Dealloc,
1227 ObjKind::ObjC));
1228 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
1229
1230 // Create the "autorelease" selector.
1231 Summ = getPersistentSummary(NoRet, ScratchArgs, ArgEffect(Autorelease,
1232 ObjKind::ObjC));
1233 addNSObjectMethSummary(GetNullarySelector("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(RetEffect::MakeNoRet(), ScratchArgs,
1241 ArgEffect(StopTracking), ArgEffect(StopTracking));
1242
1243 addClassMethSummary("NSWindow", "alloc", 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("NSPanel", "alloc", NoTrackYet);
1250
1251 // For NSNull, objects returned by +null are singletons that ignore
1252 // retain/release semantics. Just don't track them.
1253 addClassMethSummary("NSNull", "null", NoTrackYet);
1254
1255 // Don't track allocated autorelease pools, as it is okay to prematurely
1256 // exit a method.
1257 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
1258 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
1259 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
1260
1261 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1262 addInstMethSummary("QCRenderer", AllocSumm, "createSnapshotImageOfType");
1263 addInstMethSummary("QCView", AllocSumm, "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("CIContext", CFAllocSumm, "createCGImage", "fromRect");
1269 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect",
1270 "format", "colorSpace");
1271 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "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, ResultTy, *CachedSummaries);
1287}
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
static bool isSubclass(const ObjCInterfaceDecl *Class, const IdentifierInfo *II)
static bool isOSObjectRelated(const CXXMethodDecl *MD)
A function is OSObject related if it is declared on a subclass of OSObject, or any of the parameters ...
static bool isISLObjectRef(QualType Ty)
static bool isRelease(const FunctionDecl *FD, StringRef FName)
static bool hasTypedefNamed(QualType QT, StringRef Name)
static bool isOSObjectRequiredCast(StringRef S)
static ArgEffect getStopTrackingHardEquivalent(ArgEffect E)
static constexpr bool isOneOf()
static bool isOSIteratorSubclass(const Decl *D)
static QualType getCallableReturnType(const NamedDecl *ND)
static bool isAutorelease(const FunctionDecl *FD, StringRef FName)
static bool isExactClass(const Decl *D, StringRef ClassName)
static bool isOSObjectPtr(QualType QT)
static bool hasRCAnnotation(const Decl *D, StringRef rcAnnotation)
static bool isOSObjectSubclass(const Decl *D)
static bool isOSObjectThisCast(StringRef S)
static bool isMakeCollectable(StringRef FName)
static bool isOSObjectDynamicCast(StringRef S)
static bool isRetain(const FunctionDecl *FD, StringRef FName)
An instance of this class corresponds to a call.
Definition AnyCall.h:26
@ Destructor
An implicit C++ destructor call (called implicitly or by operator 'delete')
Definition AnyCall.h:40
@ ObjCMethod
A call to an Objective-C method.
Definition AnyCall.h:33
@ Deallocator
A C++ deallocation function call (operator delete), via C++ delete-expression.
Definition AnyCall.h:53
@ Function
A function, function pointer, or a C++ method call.
Definition AnyCall.h:30
@ Allocator
A C++ allocation function call (operator new), via C++ new-expression.
Definition AnyCall.h:49
@ Constructor
An implicit or explicit C++ constructor call.
Definition AnyCall.h:43
@ InheritedConstructor
A C++ inherited constructor produced by a "using T::T" directive.
Definition AnyCall.h:46
@ Block
A call to an Objective-C block.
Definition AnyCall.h:36
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2943
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3134
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1602
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
bool hasAttr() const
Definition DeclBase.h:577
QualType getType() const
Definition Expr.h:144
Represents a function declaration or definition.
Definition Decl.h:2000
param_iterator param_end()
Definition Decl.h:2787
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
param_iterator param_begin()
Definition Decl.h:2786
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2282
size_t param_size() const
Definition Decl.h:2790
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5269
unsigned getNumParams() const
Definition TypeBase.h:5547
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4465
QualType getReturnType() const
Definition TypeBase.h:4805
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
ObjCMethodDecl * getInstanceMethod(Selector Sel, bool AllowHidden=false) const
Definition DeclObjC.h:1066
Selector getSelector() const
Definition ExprObjC.cpp:289
bool isInstanceMessage() const
Determine whether this is an instance message to either a computed object or to super.
Definition ExprObjC.h:1253
ObjCInterfaceDecl * getReceiverInterface() const
Retrieve the Objective-C interface to which this message is being directed, if known.
Definition ExprObjC.cpp:310
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1361
param_const_iterator param_end() const
Definition DeclObjC.h:358
param_const_iterator param_begin() const
Definition DeclObjC.h:354
Selector getSelector() const
Definition DeclObjC.h:327
bool isInstanceMethod() const
Definition DeclObjC.h:426
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
QualType getReturnType() const
Definition DeclObjC.h:329
ObjCInterfaceDecl * getClassInterface()
Represents a parameter to a function.
Definition Decl.h:1790
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
QualType getCanonicalType() const
Definition TypeBase.h:8344
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isKeywordSelector() const
ObjCMethodFamily getMethodFamily() const
Derive the conventional family of this method.
unsigned getNumArgs() const
bool isVoidType() const
Definition TypeBase.h:8891
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isPointerType() const
Definition TypeBase.h:8529
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9178
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1910
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isObjCIdType() const
Definition TypeBase.h:8737
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9111
QualType getType() const
Definition Decl.h:723
An ArgEffect summarizes the retain count behavior on an argument or receiver to a function or method.
ArgEffect withKind(ArgEffectKind NewK)
ArgEffectKind getKind() const
static RetEffect MakeNotOwned(ObjKind o)
static RetEffect MakeOwned(ObjKind o)
@ NoRet
Indicates that no retain count information is tracked for the return value.
static RetEffect MakeNoRetHard()
bool isTrustedReferenceCountImplementation(const Decl *FD)
std::optional< BehaviorSummary > canEval(const CallExpr *CE, const FunctionDecl *FD, bool &hasTrustedImplementationAnnotation)
static bool isKnownSmartPointer(QualType QT)
const RetainSummary * getSummary(AnyCall C, bool HasNonZeroCallbackArg=false, bool IsReceiverUnconsumedSelf=false, QualType ReceiverType={})
Summary for a function with respect to ownership changes.
ArgEffect getReceiverEffect() const
getReceiverEffect - Returns the effect on the receiver of the call.
RetEffect getRetEffect() const
getRetEffect - Returns the effect on the return value of the call.
bool isSimple() const
A retain summary is simple if it has no ArgEffects other than the default.
void Profile(llvm::FoldingSetNodeID &ID) const
Profile this summary for inclusion in a FoldingSet.
internal::Matcher< Decl > DeclarationMatcher
Types of matchers for the top-level classes in the AST class hierarchy.
internal::Matcher< NamedDecl > hasName(StringRef Name)
Matches NamedDecl nodes that have the specified name.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicDynCastAllOfMatcher< Decl, CXXRecordDecl > cxxRecordDecl
Matches C++ class declarations.
bool isCocoaObjectRef(QualType T)
bool isRefType(QualType RetTy, StringRef Prefix, StringRef Name=StringRef())
bool followsCreateRule(const FunctionDecl *FD)
llvm::ImmutableMap< unsigned, ArgEffect > ArgEffects
ArgEffects summarizes the effects of a function/method call on all of its arguments.
ObjKind
Determines the object kind of a tracked object.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ Generalized
Indicates that the tracked object is a generalized object.
@ CF
Indicates that the tracked object is a CF object.
@ AnyObj
Indicates that the tracked object could be a CF or Objective-C object.
@ ObjC
Indicates that the tracked object is an Objective-C object.
@ IncRef
The argument has its reference count increased by 1.
@ UnretainedOutParameter
The argument is a pointer to a retain-counted object; on exit, the new value of the pointer is a +0 v...
@ DoNothing
There is no effect.
@ RetainedOutParameter
The argument is a pointer to a retain-counted object; on exit, the new value of the pointer is a +1 v...
@ RetainedOutParameterOnZero
The argument is a pointer to a retain-counted object; on exit, the new value of the pointer is a +1 v...
@ MayEscape
The argument is treated as potentially escaping, meaning that even when its reference count hits 0 it...
@ StopTracking
All typestate tracking of the object ceases.
@ Dealloc
The argument is treated as if the referenced object was deallocated.
@ Autorelease
The argument is treated as if an -autorelease message had been sent to the referenced object.
@ RetainedOutParameterOnNonZero
The argument is a pointer to a retain-counted object; on exit, the new value of the pointer is a +1 v...
@ DecRef
The argument has its reference count decreased by 1.
@ StopTrackingHard
All typestate tracking of the object ceases.
@ DecRefAndStopTrackingHard
Performs the combined functionality of DecRef and StopTrackingHard.
@ DecRefBridgedTransferred
The argument has its reference count decreased by 1 to model a transferred bridge cast under ARC.
bool NoRet(InterpState &S, CodePtr OpPC)
Definition Interp.h:3075
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ OMF_performSelector
@ OMF_None
No particular method family.
static bool classof(const Stmt *T)
Selector GetUnarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing an unary selector.
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
Selector GetNullarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing a nullary selector.
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5879