RetainSummaryManager.cpp 48 KB

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