blob: d5d56e395c2a150f7002043187ec2cd7faf995b1 [file] [log] [blame]
George Karpenkov70c2ee32018-08-17 21:41:07 +00001//== RetainCountSummaries.cpp - Checks for leaks and other issues -*- C++ -*--//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines summaries implementation for RetainCountChecker, which
11// implements a reference count checker for Core Foundation and Cocoa
12// on (Mac OS X).
13//
14//===----------------------------------------------------------------------===//
15
16#include "RetainCountSummaries.h"
17#include "RetainCountChecker.h"
18
19#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/ParentMap.h"
24
25using namespace objc_retain;
26using namespace clang;
27using namespace ento;
28using namespace retaincountchecker;
29
30ArgEffects RetainSummaryManager::getArgEffects() {
31 ArgEffects AE = ScratchArgs;
32 ScratchArgs = AF.getEmptyMap();
33 return AE;
34}
35
36const RetainSummary *
37RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
38 // Unique "simple" summaries -- those without ArgEffects.
39 if (OldSumm.isSimple()) {
40 ::llvm::FoldingSetNodeID ID;
41 OldSumm.Profile(ID);
42
43 void *Pos;
44 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
45
46 if (!N) {
47 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
48 new (N) CachedSummaryNode(OldSumm);
49 SimpleSummaries.InsertNode(N, Pos);
50 }
51
52 return &N->getValue();
53 }
54
55 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
56 new (Summ) RetainSummary(OldSumm);
57 return Summ;
58}
59
George Karpenkovc4d6b932018-08-17 21:42:05 +000060static bool hasRCAnnotation(const Decl *D, StringRef rcAnnotation) {
61 for (const auto *Ann : D->specific_attrs<AnnotateAttr>()) {
62 if (Ann->getAnnotation() == rcAnnotation)
63 return true;
64 }
65 return false;
66}
67
68static bool isRetain(const FunctionDecl *FD, StringRef FName) {
69 return FName.startswith_lower("retain") || FName.endswith_lower("retain");
70}
71
72static bool isRelease(const FunctionDecl *FD, StringRef FName) {
73 return FName.startswith_lower("release") || FName.endswith_lower("release");
74}
75
76static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
77 return FName.startswith_lower("autorelease") ||
78 FName.endswith_lower("autorelease");
79}
80
George Karpenkov70c2ee32018-08-17 21:41:07 +000081const RetainSummary *
George Karpenkovcab604e2018-08-17 21:41:37 +000082RetainSummaryManager::generateSummary(const FunctionDecl *FD,
83 bool &AllowAnnotations) {
84 // We generate "stop" summaries for implicitly defined functions.
85 if (FD->isImplicit()) {
86 return getPersistentStopSummary();
87 }
88
89 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
90 // function's type.
91 const FunctionType *FT = FD->getType()->getAs<FunctionType>();
92 const IdentifierInfo *II = FD->getIdentifier();
93 if (!II)
94 return getDefaultSummary();
95
96 StringRef FName = II->getName();
97
98 // Strip away preceding '_'. Doing this here will effect all the checks
99 // down below.
100 FName = FName.substr(FName.find_first_not_of('_'));
101
102 // Inspect the result type.
103 QualType RetTy = FT->getReturnType();
104 std::string RetTyName = RetTy.getAsString();
105
106 // FIXME: This should all be refactored into a chain of "summary lookup"
107 // filters.
108 assert(ScratchArgs.isEmpty());
109
110 if (FName == "pthread_create" || FName == "pthread_setspecific") {
111 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
112 // This will be addressed better with IPA.
113 return getPersistentStopSummary();
114 } else if (FName == "CFPlugInInstanceCreate") {
115 return getPersistentSummary(RetEffect::MakeNoRet());
116 } else if (FName == "IORegistryEntrySearchCFProperty" ||
117 (RetTyName == "CFMutableDictionaryRef" &&
118 (FName == "IOBSDNameMatching" || FName == "IOServiceMatching" ||
119 FName == "IOServiceNameMatching" ||
120 FName == "IORegistryEntryIDMatching" ||
121 FName == "IOOpenFirmwarePathMatching"))) {
122 // Part of <rdar://problem/6961230>. (IOKit)
123 // This should be addressed using a API table.
124 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF), DoNothing,
125 DoNothing);
126 } else if (FName == "IOServiceGetMatchingService" ||
127 FName == "IOServiceGetMatchingServices") {
128 // FIXES: <rdar://problem/6326900>
129 // This should be addressed using a API table. This strcmp is also
130 // a little gross, but there is no need to super optimize here.
131 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
132 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
133 } else if (FName == "IOServiceAddNotification" ||
134 FName == "IOServiceAddMatchingNotification") {
135 // Part of <rdar://problem/6961230>. (IOKit)
136 // This should be addressed using a API table.
137 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
138 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
139 } else if (FName == "CVPixelBufferCreateWithBytes") {
140 // FIXES: <rdar://problem/7283567>
141 // Eventually this can be improved by recognizing that the pixel
142 // buffer passed to CVPixelBufferCreateWithBytes is released via
143 // a callback and doing full IPA to make sure this is done correctly.
144 // FIXME: This function has an out parameter that returns an
145 // allocated object.
146 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
147 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
148 } else if (FName == "CGBitmapContextCreateWithData") {
149 // FIXES: <rdar://problem/7358899>
150 // Eventually this can be improved by recognizing that 'releaseInfo'
151 // passed to CGBitmapContextCreateWithData is released via
152 // a callback and doing full IPA to make sure this is done correctly.
153 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
154 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF), DoNothing,
155 DoNothing);
156 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
157 // FIXES: <rdar://problem/7283567>
158 // Eventually this can be improved by recognizing that the pixel
159 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
160 // via a callback and doing full IPA to make sure this is done
161 // correctly.
162 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
163 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
164 } else if (FName == "VTCompressionSessionEncodeFrame") {
165 // The context argument passed to VTCompressionSessionEncodeFrame()
166 // is passed to the callback specified when creating the session
167 // (e.g. with VTCompressionSessionCreate()) which can release it.
168 // To account for this possibility, conservatively stop tracking
169 // the context.
170 ScratchArgs = AF.add(ScratchArgs, 5, StopTracking);
171 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
172 } else if (FName == "dispatch_set_context" ||
173 FName == "xpc_connection_set_context") {
174 // <rdar://problem/11059275> - The analyzer currently doesn't have
175 // a good way to reason about the finalizer function for libdispatch.
176 // If we pass a context object that is memory managed, stop tracking it.
177 // <rdar://problem/13783514> - Same problem, but for XPC.
178 // FIXME: this hack should possibly go away once we can handle
179 // libdispatch and XPC finalizers.
180 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
181 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
182 } else if (FName.startswith("NSLog")) {
183 return getDoNothingSummary();
184 } else if (FName.startswith("NS") &&
185 (FName.find("Insert") != StringRef::npos)) {
186 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
187 // be deallocated by NSMapRemove. (radar://11152419)
188 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
189 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
190 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
191 }
192
193 if (RetTy->isPointerType()) {
194 // For CoreFoundation ('CF') types.
195 if (cocoa::isRefType(RetTy, "CF", FName)) {
George Karpenkovc4d6b932018-08-17 21:42:05 +0000196 if (isRetain(FD, FName)) {
George Karpenkovcab604e2018-08-17 21:41:37 +0000197 // CFRetain isn't supposed to be annotated. However, this may as well
198 // be a user-made "safe" CFRetain function that is incorrectly
199 // annotated as cf_returns_retained due to lack of better options.
200 // We want to ignore such annotation.
201 AllowAnnotations = false;
202
203 return getUnarySummary(FT, cfretain);
George Karpenkovc4d6b932018-08-17 21:42:05 +0000204 } else if (isAutorelease(FD, FName)) {
George Karpenkovcab604e2018-08-17 21:41:37 +0000205 // The headers use cf_consumed, but we can fully model CFAutorelease
206 // ourselves.
207 AllowAnnotations = false;
208
209 return getUnarySummary(FT, cfautorelease);
210 } else {
211 return getCFCreateGetRuleSummary(FD);
212 }
213 }
214
215 // For CoreGraphics ('CG') and CoreVideo ('CV') types.
216 if (cocoa::isRefType(RetTy, "CG", FName) ||
217 cocoa::isRefType(RetTy, "CV", FName)) {
George Karpenkovc4d6b932018-08-17 21:42:05 +0000218 if (isRetain(FD, FName))
George Karpenkovcab604e2018-08-17 21:41:37 +0000219 return getUnarySummary(FT, cfretain);
220 else
221 return getCFCreateGetRuleSummary(FD);
222 }
223
224 // For all other CF-style types, use the Create/Get
225 // rule for summaries but don't support Retain functions
226 // with framework-specific prefixes.
227 if (coreFoundation::isCFObjectRef(RetTy)) {
228 return getCFCreateGetRuleSummary(FD);
229 }
230
231 if (FD->hasAttr<CFAuditedTransferAttr>()) {
232 return getCFCreateGetRuleSummary(FD);
233 }
234 }
235
236 // Check for release functions, the only kind of functions that we care
237 // about that don't return a pointer type.
238 if (FName.size() >= 2 && FName[0] == 'C' &&
239 (FName[1] == 'F' || FName[1] == 'G')) {
240 // Test for 'CGCF'.
241 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
242
George Karpenkovc4d6b932018-08-17 21:42:05 +0000243 if (isRelease(FD, FName))
George Karpenkovcab604e2018-08-17 21:41:37 +0000244 return getUnarySummary(FT, cfrelease);
245 else {
246 assert(ScratchArgs.isEmpty());
247 // Remaining CoreFoundation and CoreGraphics functions.
248 // We use to assume that they all strictly followed the ownership idiom
249 // and that ownership cannot be transferred. While this is technically
250 // correct, many methods allow a tracked object to escape. For example:
251 //
252 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
253 // CFDictionaryAddValue(y, key, x);
254 // CFRelease(x);
255 // ... it is okay to use 'x' since 'y' has a reference to it
256 //
257 // We handle this and similar cases with the follow heuristic. If the
258 // function name contains "InsertValue", "SetValue", "AddValue",
259 // "AppendValue", or "SetAttribute", then we assume that arguments may
260 // "escape." This means that something else holds on to the object,
261 // allowing it be used even after its local retain count drops to 0.
262 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos ||
263 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
264 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
265 StrInStrNoCase(FName, "AppendValue") != StringRef::npos ||
266 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
267 ? MayEscape
268 : DoNothing;
269
270 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
271 }
272 }
273
274 return getDefaultSummary();
275}
276
277const RetainSummary *
George Karpenkov70c2ee32018-08-17 21:41:07 +0000278RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
279 // If we don't know what function we're calling, use our default summary.
280 if (!FD)
281 return getDefaultSummary();
282
283 // Look up a summary in our cache of FunctionDecls -> Summaries.
284 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
285 if (I != FuncSummaries.end())
286 return I->second;
287
288 // No summary? Generate one.
George Karpenkov70c2ee32018-08-17 21:41:07 +0000289 bool AllowAnnotations = true;
George Karpenkovcab604e2018-08-17 21:41:37 +0000290 const RetainSummary *S = generateSummary(FD, AllowAnnotations);
George Karpenkov70c2ee32018-08-17 21:41:07 +0000291
292 // Annotations override defaults.
293 if (AllowAnnotations)
294 updateSummaryFromAnnotations(S, FD);
295
296 FuncSummaries[FD] = S;
297 return S;
298}
299
300//===----------------------------------------------------------------------===//
301// Summary creation for functions (largely uses of Core Foundation).
302//===----------------------------------------------------------------------===//
303
304
305static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
306 switch (E) {
307 case DoNothing:
308 case Autorelease:
309 case DecRefBridgedTransferred:
310 case IncRef:
311 case IncRefMsg:
312 case UnretainedOutParameter:
313 case RetainedOutParameter:
314 case MayEscape:
315 case StopTracking:
316 case StopTrackingHard:
317 return StopTrackingHard;
318 case DecRef:
319 case DecRefAndStopTrackingHard:
320 return DecRefAndStopTrackingHard;
321 case DecRefMsg:
322 case DecRefMsgAndStopTrackingHard:
323 return DecRefMsgAndStopTrackingHard;
324 case Dealloc:
325 return Dealloc;
326 }
327
328 llvm_unreachable("Unknown ArgEffect kind");
329}
330
331void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
332 const CallEvent &Call) {
333 if (Call.hasNonZeroCallbackArg()) {
334 ArgEffect RecEffect =
335 getStopTrackingHardEquivalent(S->getReceiverEffect());
336 ArgEffect DefEffect =
337 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
338
339 ArgEffects CustomArgEffects = S->getArgEffects();
340 for (ArgEffects::iterator I = CustomArgEffects.begin(),
341 E = CustomArgEffects.end();
342 I != E; ++I) {
343 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
344 if (Translated != DefEffect)
345 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
346 }
347
348 RetEffect RE = RetEffect::MakeNoRetHard();
349
350 // Special cases where the callback argument CANNOT free the return value.
351 // This can generally only happen if we know that the callback will only be
352 // called when the return value is already being deallocated.
353 if (const SimpleFunctionCall *FC = dyn_cast<SimpleFunctionCall>(&Call)) {
354 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
355 // When the CGBitmapContext is deallocated, the callback here will free
356 // the associated data buffer.
357 // The callback in dispatch_data_create frees the buffer, but not
358 // the data object.
359 if (Name->isStr("CGBitmapContextCreateWithData") ||
360 Name->isStr("dispatch_data_create"))
361 RE = S->getRetEffect();
362 }
363 }
364
365 S = getPersistentSummary(RE, RecEffect, DefEffect);
366 }
367
368 // Special case '[super init];' and '[self init];'
369 //
370 // Even though calling '[super init]' without assigning the result to self
371 // and checking if the parent returns 'nil' is a bad pattern, it is common.
372 // Additionally, our Self Init checker already warns about it. To avoid
373 // overwhelming the user with messages from both checkers, we model the case
374 // of '[super init]' in cases when it is not consumed by another expression
375 // as if the call preserves the value of 'self'; essentially, assuming it can
376 // never fail and return 'nil'.
377 // Note, we don't want to just stop tracking the value since we want the
378 // RetainCount checker to report leaks and use-after-free if SelfInit checker
379 // is turned off.
380 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
381 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
382
383 // Check if the message is not consumed, we know it will not be used in
384 // an assignment, ex: "self = [super init]".
385 const Expr *ME = MC->getOriginExpr();
386 const LocationContext *LCtx = MC->getLocationContext();
387 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
388 if (!PM.isConsumedExpr(ME)) {
389 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
390 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
391 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
392 }
393 }
394 }
395}
396
397const RetainSummary *
398RetainSummaryManager::getSummary(const CallEvent &Call,
399 ProgramStateRef State) {
400 const RetainSummary *Summ;
401 switch (Call.getKind()) {
402 case CE_Function:
403 Summ = getFunctionSummary(cast<SimpleFunctionCall>(Call).getDecl());
404 break;
405 case CE_CXXMember:
406 case CE_CXXMemberOperator:
407 case CE_Block:
408 case CE_CXXConstructor:
409 case CE_CXXDestructor:
410 case CE_CXXAllocator:
411 // FIXME: These calls are currently unsupported.
412 return getPersistentStopSummary();
413 case CE_ObjCMessage: {
414 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
415 if (Msg.isInstanceMessage())
416 Summ = getInstanceMethodSummary(Msg, State);
417 else
418 Summ = getClassMethodSummary(Msg);
419 break;
420 }
421 }
422
423 updateSummaryForCall(Summ, Call);
424
425 assert(Summ && "Unknown call type?");
426 return Summ;
427}
428
429
430const RetainSummary *
431RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
432 if (coreFoundation::followsCreateRule(FD))
433 return getCFSummaryCreateRule(FD);
434
435 return getCFSummaryGetRule(FD);
436}
437
George Karpenkovc4d6b932018-08-17 21:42:05 +0000438bool RetainSummaryManager::isTrustedReferenceCountImplementation(
439 const FunctionDecl *FD) {
440 return hasRCAnnotation(FD, "rc_ownership_trusted_implementation");
441}
442
443bool RetainSummaryManager::canEval(const CallExpr *CE,
444 const FunctionDecl *FD,
445 bool &hasTrustedImplementationAnnotation) {
446 // For now, we're only handling the functions that return aliases of their
447 // arguments: CFRetain (and its families).
448 // Eventually we should add other functions we can model entirely,
449 // such as CFRelease, which don't invalidate their arguments or globals.
450 if (CE->getNumArgs() != 1)
451 return false;
452
453 IdentifierInfo *II = FD->getIdentifier();
454 if (!II)
455 return false;
456
457 StringRef FName = II->getName();
458 FName = FName.substr(FName.find_first_not_of('_'));
459
460 QualType ResultTy = CE->getCallReturnType(Ctx);
461 if (ResultTy->isPointerType()) {
462 // Handle: (CF|CG|CV)Retain
463 // CFAutorelease
464 // It's okay to be a little sloppy here.
465 if (cocoa::isRefType(ResultTy, "CF", FName) ||
466 cocoa::isRefType(ResultTy, "CG", FName) ||
467 cocoa::isRefType(ResultTy, "CV", FName))
468 return isRetain(FD, FName) || isAutorelease(FD, FName);
469
470 if (FD->getDefinition()) {
471 bool out = isTrustedReferenceCountImplementation(FD->getDefinition());
472 hasTrustedImplementationAnnotation = out;
473 return out;
474 }
475 }
476
477 return false;
478
479}
480
George Karpenkov70c2ee32018-08-17 21:41:07 +0000481const RetainSummary *
482RetainSummaryManager::getUnarySummary(const FunctionType* FT,
483 UnaryFuncKind func) {
484
485 // Sanity check that this is *really* a unary function. This can
486 // happen if people do weird things.
487 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
488 if (!FTP || FTP->getNumParams() != 1)
489 return getPersistentStopSummary();
490
491 assert (ScratchArgs.isEmpty());
492
493 ArgEffect Effect;
494 switch (func) {
495 case cfretain: Effect = IncRef; break;
496 case cfrelease: Effect = DecRef; break;
497 case cfautorelease: Effect = Autorelease; break;
498 }
499
500 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
501 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
502}
503
504const RetainSummary *
505RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
506 assert (ScratchArgs.isEmpty());
507
508 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF));
509}
510
511const RetainSummary *
512RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
513 assert (ScratchArgs.isEmpty());
514 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
515 DoNothing, DoNothing);
516}
517
518
519
520
521//===----------------------------------------------------------------------===//
522// Summary creation for Selectors.
523//===----------------------------------------------------------------------===//
524
525Optional<RetEffect>
526RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
527 const Decl *D) {
528 if (cocoa::isCocoaObjectRef(RetTy)) {
529 if (D->hasAttr<NSReturnsRetainedAttr>())
530 return ObjCAllocRetE;
531
532 if (D->hasAttr<NSReturnsNotRetainedAttr>() ||
533 D->hasAttr<NSReturnsAutoreleasedAttr>())
534 return RetEffect::MakeNotOwned(RetEffect::ObjC);
535
536 } else if (!RetTy->isPointerType()) {
537 return None;
538 }
539
540 if (D->hasAttr<CFReturnsRetainedAttr>())
541 return RetEffect::MakeOwned(RetEffect::CF);
George Karpenkovc4d6b932018-08-17 21:42:05 +0000542 else if (hasRCAnnotation(D, "rc_ownership_returns_retained"))
George Karpenkov70c2ee32018-08-17 21:41:07 +0000543 return RetEffect::MakeOwned(RetEffect::Generalized);
544
545 if (D->hasAttr<CFReturnsNotRetainedAttr>())
546 return RetEffect::MakeNotOwned(RetEffect::CF);
547
548 return None;
549}
550
551void
552RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
553 const FunctionDecl *FD) {
554 if (!FD)
555 return;
556
557 assert(Summ && "Must have a summary to add annotations to.");
558 RetainSummaryTemplate Template(Summ, *this);
559
560 // Effects on the parameters.
561 unsigned parm_idx = 0;
562 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
563 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
564 const ParmVarDecl *pd = *pi;
565 if (pd->hasAttr<NSConsumedAttr>())
566 Template->addArg(AF, parm_idx, DecRefMsg);
567 else if (pd->hasAttr<CFConsumedAttr>() ||
George Karpenkovc4d6b932018-08-17 21:42:05 +0000568 hasRCAnnotation(pd, "rc_ownership_consumed"))
George Karpenkov70c2ee32018-08-17 21:41:07 +0000569 Template->addArg(AF, parm_idx, DecRef);
570 else if (pd->hasAttr<CFReturnsRetainedAttr>() ||
George Karpenkovc4d6b932018-08-17 21:42:05 +0000571 hasRCAnnotation(pd, "rc_ownership_returns_retained")) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000572 QualType PointeeTy = pd->getType()->getPointeeType();
573 if (!PointeeTy.isNull())
574 if (coreFoundation::isCFObjectRef(PointeeTy))
575 Template->addArg(AF, parm_idx, RetainedOutParameter);
576 } else if (pd->hasAttr<CFReturnsNotRetainedAttr>()) {
577 QualType PointeeTy = pd->getType()->getPointeeType();
578 if (!PointeeTy.isNull())
579 if (coreFoundation::isCFObjectRef(PointeeTy))
580 Template->addArg(AF, parm_idx, UnretainedOutParameter);
581 }
582 }
583
584 QualType RetTy = FD->getReturnType();
585 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
586 Template->setRetEffect(*RetE);
587}
588
589void
590RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
591 const ObjCMethodDecl *MD) {
592 if (!MD)
593 return;
594
595 assert(Summ && "Must have a valid summary to add annotations to");
596 RetainSummaryTemplate Template(Summ, *this);
597
598 // Effects on the receiver.
599 if (MD->hasAttr<NSConsumesSelfAttr>())
600 Template->setReceiverEffect(DecRefMsg);
601
602 // Effects on the parameters.
603 unsigned parm_idx = 0;
604 for (ObjCMethodDecl::param_const_iterator
605 pi=MD->param_begin(), pe=MD->param_end();
606 pi != pe; ++pi, ++parm_idx) {
607 const ParmVarDecl *pd = *pi;
608 if (pd->hasAttr<NSConsumedAttr>())
609 Template->addArg(AF, parm_idx, DecRefMsg);
610 else if (pd->hasAttr<CFConsumedAttr>()) {
611 Template->addArg(AF, parm_idx, DecRef);
612 } else if (pd->hasAttr<CFReturnsRetainedAttr>()) {
613 QualType PointeeTy = pd->getType()->getPointeeType();
614 if (!PointeeTy.isNull())
615 if (coreFoundation::isCFObjectRef(PointeeTy))
616 Template->addArg(AF, parm_idx, RetainedOutParameter);
617 } else if (pd->hasAttr<CFReturnsNotRetainedAttr>()) {
618 QualType PointeeTy = pd->getType()->getPointeeType();
619 if (!PointeeTy.isNull())
620 if (coreFoundation::isCFObjectRef(PointeeTy))
621 Template->addArg(AF, parm_idx, UnretainedOutParameter);
622 }
623 }
624
625 QualType RetTy = MD->getReturnType();
626 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
627 Template->setRetEffect(*RetE);
628}
629
630const RetainSummary *
631RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
632 Selector S, QualType RetTy) {
633 // Any special effects?
634 ArgEffect ReceiverEff = DoNothing;
635 RetEffect ResultEff = RetEffect::MakeNoRet();
636
637 // Check the method family, and apply any default annotations.
638 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
639 case OMF_None:
640 case OMF_initialize:
641 case OMF_performSelector:
642 // Assume all Objective-C methods follow Cocoa Memory Management rules.
643 // FIXME: Does the non-threaded performSelector family really belong here?
644 // The selector could be, say, @selector(copy).
645 if (cocoa::isCocoaObjectRef(RetTy))
646 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
647 else if (coreFoundation::isCFObjectRef(RetTy)) {
648 // ObjCMethodDecl currently doesn't consider CF objects as valid return
649 // values for alloc, new, copy, or mutableCopy, so we have to
650 // double-check with the selector. This is ugly, but there aren't that
651 // many Objective-C methods that return CF objects, right?
652 if (MD) {
653 switch (S.getMethodFamily()) {
654 case OMF_alloc:
655 case OMF_new:
656 case OMF_copy:
657 case OMF_mutableCopy:
658 ResultEff = RetEffect::MakeOwned(RetEffect::CF);
659 break;
660 default:
661 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
662 break;
663 }
664 } else {
665 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
666 }
667 }
668 break;
669 case OMF_init:
670 ResultEff = ObjCInitRetE;
671 ReceiverEff = DecRefMsg;
672 break;
673 case OMF_alloc:
674 case OMF_new:
675 case OMF_copy:
676 case OMF_mutableCopy:
677 if (cocoa::isCocoaObjectRef(RetTy))
678 ResultEff = ObjCAllocRetE;
679 else if (coreFoundation::isCFObjectRef(RetTy))
680 ResultEff = RetEffect::MakeOwned(RetEffect::CF);
681 break;
682 case OMF_autorelease:
683 ReceiverEff = Autorelease;
684 break;
685 case OMF_retain:
686 ReceiverEff = IncRefMsg;
687 break;
688 case OMF_release:
689 ReceiverEff = DecRefMsg;
690 break;
691 case OMF_dealloc:
692 ReceiverEff = Dealloc;
693 break;
694 case OMF_self:
695 // -self is handled specially by the ExprEngine to propagate the receiver.
696 break;
697 case OMF_retainCount:
698 case OMF_finalize:
699 // These methods don't return objects.
700 break;
701 }
702
703 // If one of the arguments in the selector has the keyword 'delegate' we
704 // should stop tracking the reference count for the receiver. This is
705 // because the reference count is quite possibly handled by a delegate
706 // method.
707 if (S.isKeywordSelector()) {
708 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
709 StringRef Slot = S.getNameForSlot(i);
710 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
711 if (ResultEff == ObjCInitRetE)
712 ResultEff = RetEffect::MakeNoRetHard();
713 else
714 ReceiverEff = StopTrackingHard;
715 }
716 }
717 }
718
719 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
720 ResultEff.getKind() == RetEffect::NoRet)
721 return getDefaultSummary();
722
723 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
724}
725
726const RetainSummary *
727RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
728 ProgramStateRef State) {
729 const ObjCInterfaceDecl *ReceiverClass = nullptr;
730
731 // We do better tracking of the type of the object than the core ExprEngine.
732 // See if we have its type in our private state.
733 // FIXME: Eventually replace the use of state->get<RefBindings> with
734 // a generic API for reasoning about the Objective-C types of symbolic
735 // objects.
736 SVal ReceiverV = Msg.getReceiverSVal();
737 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
738 if (const RefVal *T = getRefBinding(State, Sym))
739 if (const ObjCObjectPointerType *PT =
740 T->getType()->getAs<ObjCObjectPointerType>())
741 ReceiverClass = PT->getInterfaceDecl();
742
743 // If we don't know what kind of object this is, fall back to its static type.
744 if (!ReceiverClass)
745 ReceiverClass = Msg.getReceiverInterface();
746
747 // FIXME: The receiver could be a reference to a class, meaning that
748 // we should use the class method.
749 // id x = [NSObject class];
750 // [x performSelector:... withObject:... afterDelay:...];
751 Selector S = Msg.getSelector();
752 const ObjCMethodDecl *Method = Msg.getDecl();
753 if (!Method && ReceiverClass)
754 Method = ReceiverClass->getInstanceMethod(S);
755
756 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
757 ObjCMethodSummaries);
758}
759
760const RetainSummary *
761RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
762 const ObjCMethodDecl *MD, QualType RetTy,
763 ObjCMethodSummariesTy &CachedSummaries) {
764
765 // Look up a summary in our summary cache.
766 const RetainSummary *Summ = CachedSummaries.find(ID, S);
767
768 if (!Summ) {
769 Summ = getStandardMethodSummary(MD, S, RetTy);
770
771 // Annotations override defaults.
772 updateSummaryFromAnnotations(Summ, MD);
773
774 // Memoize the summary.
775 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
776 }
777
778 return Summ;
779}
780
781void RetainSummaryManager::InitializeClassMethodSummaries() {
782 assert(ScratchArgs.isEmpty());
783 // Create the [NSAssertionHandler currentHander] summary.
784 addClassMethSummary("NSAssertionHandler", "currentHandler",
785 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
786
787 // Create the [NSAutoreleasePool addObject:] summary.
788 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
789 addClassMethSummary("NSAutoreleasePool", "addObject",
790 getPersistentSummary(RetEffect::MakeNoRet(),
791 DoNothing, Autorelease));
792}
793
794void RetainSummaryManager::InitializeMethodSummaries() {
795
796 assert (ScratchArgs.isEmpty());
797
798 // Create the "init" selector. It just acts as a pass-through for the
799 // receiver.
800 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
801 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
802
803 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
804 // claims the receiver and returns a retained object.
805 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
806 InitSumm);
807
808 // The next methods are allocators.
809 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
810 const RetainSummary *CFAllocSumm =
811 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF));
812
813 // Create the "retain" selector.
814 RetEffect NoRet = RetEffect::MakeNoRet();
815 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
816 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
817
818 // Create the "release" selector.
819 Summ = getPersistentSummary(NoRet, DecRefMsg);
820 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
821
822 // Create the -dealloc summary.
823 Summ = getPersistentSummary(NoRet, Dealloc);
824 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
825
826 // Create the "autorelease" selector.
827 Summ = getPersistentSummary(NoRet, Autorelease);
828 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
829
830 // For NSWindow, allocated objects are (initially) self-owned.
831 // FIXME: For now we opt for false negatives with NSWindow, as these objects
832 // self-own themselves. However, they only do this once they are displayed.
833 // Thus, we need to track an NSWindow's display status.
834 // This is tracked in <rdar://problem/6062711>.
835 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
836 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
837 StopTracking,
838 StopTracking);
839
840 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
841
842 // For NSPanel (which subclasses NSWindow), allocated objects are not
843 // self-owned.
844 // FIXME: For now we don't track NSPanels. object for the same reason
845 // as for NSWindow objects.
846 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
847
848 // For NSNull, objects returned by +null are singletons that ignore
849 // retain/release semantics. Just don't track them.
850 // <rdar://problem/12858915>
851 addClassMethSummary("NSNull", "null", NoTrackYet);
852
853 // Don't track allocated autorelease pools, as it is okay to prematurely
854 // exit a method.
855 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
856 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
857 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
858
859 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
860 addInstMethSummary("QCRenderer", AllocSumm, "createSnapshotImageOfType");
861 addInstMethSummary("QCView", AllocSumm, "createSnapshotImageOfType");
862
863 // Create summaries for CIContext, 'createCGImage' and
864 // 'createCGLayerWithSize'. These objects are CF objects, and are not
865 // automatically garbage collected.
866 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect");
867 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect",
868 "format", "colorSpace");
869 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info");
870}