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