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