RetainSummaryManager.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //=== RetainSummaryManager.h - Summaries for reference counting ---*- C++ -*--//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines summaries implementation for retain counting, which
  15. // implements a reference count checker for Core Foundation and Cocoa
  16. // on (Mac OS X).
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_CLANG_ANALYSIS_RETAINSUMMARYMANAGER_H
  20. #define LLVM_CLANG_ANALYSIS_RETAINSUMMARYMANAGER_H
  21. #include "llvm/ADT/DenseMap.h"
  22. #include "llvm/ADT/FoldingSet.h"
  23. #include "llvm/ADT/ImmutableMap.h"
  24. #include "clang/AST/Attr.h"
  25. #include "clang/AST/DeclCXX.h"
  26. #include "clang/AST/DeclObjC.h"
  27. #include "clang/AST/ParentMap.h"
  28. #include "clang/Analysis/AnyCall.h"
  29. #include "clang/Analysis/SelectorExtras.h"
  30. #include "llvm/ADT/STLExtras.h"
  31. #include <optional>
  32. using namespace clang;
  33. namespace clang {
  34. namespace ento {
  35. /// Determines the object kind of a tracked object.
  36. enum class ObjKind {
  37. /// Indicates that the tracked object is a CF object.
  38. CF,
  39. /// Indicates that the tracked object is an Objective-C object.
  40. ObjC,
  41. /// Indicates that the tracked object could be a CF or Objective-C object.
  42. AnyObj,
  43. /// Indicates that the tracked object is a generalized object.
  44. Generalized,
  45. /// Indicates that the tracking object is a descendant of a
  46. /// referenced-counted OSObject, used in the Darwin kernel.
  47. OS
  48. };
  49. enum ArgEffectKind {
  50. /// There is no effect.
  51. DoNothing,
  52. /// The argument is treated as if an -autorelease message had been sent to
  53. /// the referenced object.
  54. Autorelease,
  55. /// The argument is treated as if the referenced object was deallocated.
  56. Dealloc,
  57. /// The argument has its reference count decreased by 1.
  58. DecRef,
  59. /// The argument has its reference count decreased by 1 to model
  60. /// a transferred bridge cast under ARC.
  61. DecRefBridgedTransferred,
  62. /// The argument has its reference count increased by 1.
  63. IncRef,
  64. /// The argument is a pointer to a retain-counted object; on exit, the new
  65. /// value of the pointer is a +0 value.
  66. UnretainedOutParameter,
  67. /// The argument is a pointer to a retain-counted object; on exit, the new
  68. /// value of the pointer is a +1 value.
  69. RetainedOutParameter,
  70. /// The argument is a pointer to a retain-counted object; on exit, the new
  71. /// value of the pointer is a +1 value iff the return code is zero.
  72. RetainedOutParameterOnZero,
  73. /// The argument is a pointer to a retain-counted object; on exit, the new
  74. /// value of the pointer is a +1 value iff the return code is non-zero.
  75. RetainedOutParameterOnNonZero,
  76. /// The argument is treated as potentially escaping, meaning that
  77. /// even when its reference count hits 0 it should be treated as still
  78. /// possibly being alive as someone else *may* be holding onto the object.
  79. MayEscape,
  80. /// All typestate tracking of the object ceases. This is usually employed
  81. /// when the effect of the call is completely unknown.
  82. StopTracking,
  83. /// All typestate tracking of the object ceases. Unlike StopTracking,
  84. /// this is also enforced when the method body is inlined.
  85. ///
  86. /// In some cases, we obtain a better summary for this checker
  87. /// by looking at the call site than by inlining the function.
  88. /// Signifies that we should stop tracking the symbol even if
  89. /// the function is inlined.
  90. StopTrackingHard,
  91. /// Performs the combined functionality of DecRef and StopTrackingHard.
  92. ///
  93. /// The models the effect that the called function decrements the reference
  94. /// count of the argument and all typestate tracking on that argument
  95. /// should cease.
  96. DecRefAndStopTrackingHard,
  97. };
  98. /// An ArgEffect summarizes the retain count behavior on an argument or receiver
  99. /// to a function or method.
  100. class ArgEffect {
  101. ArgEffectKind K;
  102. ObjKind O;
  103. public:
  104. explicit ArgEffect(ArgEffectKind K = DoNothing, ObjKind O = ObjKind::AnyObj)
  105. : K(K), O(O) {}
  106. ArgEffectKind getKind() const { return K; }
  107. ObjKind getObjKind() const { return O; }
  108. ArgEffect withKind(ArgEffectKind NewK) {
  109. return ArgEffect(NewK, O);
  110. }
  111. bool operator==(const ArgEffect &Other) const {
  112. return K == Other.K && O == Other.O;
  113. }
  114. };
  115. /// RetEffect summarizes a call's retain/release behavior with respect
  116. /// to its return value.
  117. class RetEffect {
  118. public:
  119. enum Kind {
  120. /// Indicates that no retain count information is tracked for
  121. /// the return value.
  122. NoRet,
  123. /// Indicates that the returned value is an owned (+1) symbol.
  124. OwnedSymbol,
  125. /// Indicates that the returned value is an object with retain count
  126. /// semantics but that it is not owned (+0). This is the default
  127. /// for getters, etc.
  128. NotOwnedSymbol,
  129. /// Indicates that the return value is an owned object when the
  130. /// receiver is also a tracked object.
  131. OwnedWhenTrackedReceiver,
  132. // Treat this function as returning a non-tracked symbol even if
  133. // the function has been inlined. This is used where the call
  134. // site summary is more precise than the summary indirectly produced
  135. // by inlining the function
  136. NoRetHard
  137. };
  138. private:
  139. Kind K;
  140. ObjKind O;
  141. RetEffect(Kind k, ObjKind o = ObjKind::AnyObj) : K(k), O(o) {}
  142. public:
  143. Kind getKind() const { return K; }
  144. ObjKind getObjKind() const { return O; }
  145. bool isOwned() const {
  146. return K == OwnedSymbol || K == OwnedWhenTrackedReceiver;
  147. }
  148. bool notOwned() const {
  149. return K == NotOwnedSymbol;
  150. }
  151. bool operator==(const RetEffect &Other) const {
  152. return K == Other.K && O == Other.O;
  153. }
  154. static RetEffect MakeOwnedWhenTrackedReceiver() {
  155. return RetEffect(OwnedWhenTrackedReceiver, ObjKind::ObjC);
  156. }
  157. static RetEffect MakeOwned(ObjKind o) {
  158. return RetEffect(OwnedSymbol, o);
  159. }
  160. static RetEffect MakeNotOwned(ObjKind o) {
  161. return RetEffect(NotOwnedSymbol, o);
  162. }
  163. static RetEffect MakeNoRet() {
  164. return RetEffect(NoRet);
  165. }
  166. static RetEffect MakeNoRetHard() {
  167. return RetEffect(NoRetHard);
  168. }
  169. };
  170. /// A key identifying a summary.
  171. class ObjCSummaryKey {
  172. IdentifierInfo* II;
  173. Selector S;
  174. public:
  175. ObjCSummaryKey(IdentifierInfo* ii, Selector s)
  176. : II(ii), S(s) {}
  177. ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
  178. : II(d ? d->getIdentifier() : nullptr), S(s) {}
  179. ObjCSummaryKey(Selector s)
  180. : II(nullptr), S(s) {}
  181. IdentifierInfo *getIdentifier() const { return II; }
  182. Selector getSelector() const { return S; }
  183. };
  184. } // end namespace ento
  185. } // end namespace clang
  186. using namespace ento;
  187. namespace llvm {
  188. //===----------------------------------------------------------------------===//
  189. // Adapters for FoldingSet.
  190. //===----------------------------------------------------------------------===//
  191. template <> struct FoldingSetTrait<ArgEffect> {
  192. static inline void Profile(const ArgEffect X, FoldingSetNodeID &ID) {
  193. ID.AddInteger((unsigned) X.getKind());
  194. ID.AddInteger((unsigned) X.getObjKind());
  195. }
  196. };
  197. template <> struct FoldingSetTrait<RetEffect> {
  198. static inline void Profile(const RetEffect &X, FoldingSetNodeID &ID) {
  199. ID.AddInteger((unsigned) X.getKind());
  200. ID.AddInteger((unsigned) X.getObjKind());
  201. }
  202. };
  203. template <> struct DenseMapInfo<ObjCSummaryKey> {
  204. static inline ObjCSummaryKey getEmptyKey() {
  205. return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
  206. DenseMapInfo<Selector>::getEmptyKey());
  207. }
  208. static inline ObjCSummaryKey getTombstoneKey() {
  209. return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
  210. DenseMapInfo<Selector>::getTombstoneKey());
  211. }
  212. static unsigned getHashValue(const ObjCSummaryKey &V) {
  213. typedef std::pair<IdentifierInfo*, Selector> PairTy;
  214. return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
  215. V.getSelector()));
  216. }
  217. static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
  218. return LHS.getIdentifier() == RHS.getIdentifier() &&
  219. LHS.getSelector() == RHS.getSelector();
  220. }
  221. };
  222. } // end llvm namespace
  223. namespace clang {
  224. namespace ento {
  225. /// ArgEffects summarizes the effects of a function/method call on all of
  226. /// its arguments.
  227. typedef llvm::ImmutableMap<unsigned, ArgEffect> ArgEffects;
  228. /// Summary for a function with respect to ownership changes.
  229. class RetainSummary {
  230. /// Args - a map of (index, ArgEffect) pairs, where index
  231. /// specifies the argument (starting from 0). This can be sparsely
  232. /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
  233. ArgEffects Args;
  234. /// DefaultArgEffect - The default ArgEffect to apply to arguments that
  235. /// do not have an entry in Args.
  236. ArgEffect DefaultArgEffect;
  237. /// Receiver - If this summary applies to an Objective-C message expression,
  238. /// this is the effect applied to the state of the receiver.
  239. ArgEffect Receiver;
  240. /// Effect on "this" pointer - applicable only to C++ method calls.
  241. ArgEffect This;
  242. /// Ret - The effect on the return value. Used to indicate if the
  243. /// function/method call returns a new tracked symbol.
  244. RetEffect Ret;
  245. public:
  246. RetainSummary(ArgEffects A,
  247. RetEffect R,
  248. ArgEffect defaultEff,
  249. ArgEffect ReceiverEff,
  250. ArgEffect ThisEff)
  251. : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff),
  252. This(ThisEff), Ret(R) {}
  253. /// getArg - Return the argument effect on the argument specified by
  254. /// idx (starting from 0).
  255. ArgEffect getArg(unsigned idx) const {
  256. if (const ArgEffect *AE = Args.lookup(idx))
  257. return *AE;
  258. return DefaultArgEffect;
  259. }
  260. void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
  261. Args = af.add(Args, idx, e);
  262. }
  263. /// setDefaultArgEffect - Set the default argument effect.
  264. void setDefaultArgEffect(ArgEffect E) {
  265. DefaultArgEffect = E;
  266. }
  267. /// getRetEffect - Returns the effect on the return value of the call.
  268. RetEffect getRetEffect() const { return Ret; }
  269. /// setRetEffect - Set the effect of the return value of the call.
  270. void setRetEffect(RetEffect E) { Ret = E; }
  271. /// Sets the effect on the receiver of the message.
  272. void setReceiverEffect(ArgEffect e) { Receiver = e; }
  273. /// getReceiverEffect - Returns the effect on the receiver of the call.
  274. /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
  275. ArgEffect getReceiverEffect() const { return Receiver; }
  276. /// \return the effect on the "this" receiver of the method call.
  277. /// This is only meaningful if the summary applies to CXXMethodDecl*.
  278. ArgEffect getThisEffect() const { return This; }
  279. ArgEffect getDefaultEffect() const { return DefaultArgEffect; }
  280. /// Set the effect of the method on "this".
  281. void setThisEffect(ArgEffect e) { This = e; }
  282. bool isNoop() const {
  283. return Ret == RetEffect::MakeNoRet() && Receiver.getKind() == DoNothing
  284. && DefaultArgEffect.getKind() == MayEscape && This.getKind() == DoNothing
  285. && Args.isEmpty();
  286. }
  287. /// Test if two retain summaries are identical. Note that merely equivalent
  288. /// summaries are not necessarily identical (for example, if an explicit
  289. /// argument effect matches the default effect).
  290. bool operator==(const RetainSummary &Other) const {
  291. return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
  292. Receiver == Other.Receiver && This == Other.This && Ret == Other.Ret;
  293. }
  294. /// Profile this summary for inclusion in a FoldingSet.
  295. void Profile(llvm::FoldingSetNodeID& ID) const {
  296. ID.Add(Args);
  297. ID.Add(DefaultArgEffect);
  298. ID.Add(Receiver);
  299. ID.Add(This);
  300. ID.Add(Ret);
  301. }
  302. /// A retain summary is simple if it has no ArgEffects other than the default.
  303. bool isSimple() const {
  304. return Args.isEmpty();
  305. }
  306. ArgEffects getArgEffects() const { return Args; }
  307. private:
  308. ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
  309. friend class RetainSummaryManager;
  310. };
  311. class ObjCSummaryCache {
  312. typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
  313. MapTy M;
  314. public:
  315. ObjCSummaryCache() {}
  316. const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
  317. // Do a lookup with the (D,S) pair. If we find a match return
  318. // the iterator.
  319. ObjCSummaryKey K(D, S);
  320. MapTy::iterator I = M.find(K);
  321. if (I != M.end())
  322. return I->second;
  323. if (!D)
  324. return nullptr;
  325. // Walk the super chain. If we find a hit with a parent, we'll end
  326. // up returning that summary. We actually allow that key (null,S), as
  327. // we cache summaries for the null ObjCInterfaceDecl* to allow us to
  328. // generate initial summaries without having to worry about NSObject
  329. // being declared.
  330. // FIXME: We may change this at some point.
  331. for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
  332. if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
  333. break;
  334. if (!C)
  335. return nullptr;
  336. }
  337. // Cache the summary with original key to make the next lookup faster
  338. // and return the iterator.
  339. const RetainSummary *Summ = I->second;
  340. M[K] = Summ;
  341. return Summ;
  342. }
  343. const RetainSummary *find(IdentifierInfo* II, Selector S) {
  344. // FIXME: Class method lookup. Right now we don't have a good way
  345. // of going between IdentifierInfo* and the class hierarchy.
  346. MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
  347. if (I == M.end())
  348. I = M.find(ObjCSummaryKey(S));
  349. return I == M.end() ? nullptr : I->second;
  350. }
  351. const RetainSummary *& operator[](ObjCSummaryKey K) {
  352. return M[K];
  353. }
  354. const RetainSummary *& operator[](Selector S) {
  355. return M[ ObjCSummaryKey(S) ];
  356. }
  357. };
  358. class RetainSummaryTemplate;
  359. class RetainSummaryManager {
  360. typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
  361. FuncSummariesTy;
  362. typedef ObjCSummaryCache ObjCMethodSummariesTy;
  363. typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
  364. /// Ctx - The ASTContext object for the analyzed ASTs.
  365. ASTContext &Ctx;
  366. /// Records whether or not the analyzed code runs in ARC mode.
  367. const bool ARCEnabled;
  368. /// Track Objective-C and CoreFoundation objects.
  369. const bool TrackObjCAndCFObjects;
  370. /// Track sublcasses of OSObject.
  371. const bool TrackOSObjects;
  372. /// FuncSummaries - A map from FunctionDecls to summaries.
  373. FuncSummariesTy FuncSummaries;
  374. /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
  375. /// to summaries.
  376. ObjCMethodSummariesTy ObjCClassMethodSummaries;
  377. /// ObjCMethodSummaries - A map from selectors to summaries.
  378. ObjCMethodSummariesTy ObjCMethodSummaries;
  379. /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
  380. /// and all other data used by the checker.
  381. llvm::BumpPtrAllocator BPAlloc;
  382. /// AF - A factory for ArgEffects objects.
  383. ArgEffects::Factory AF;
  384. /// ObjCAllocRetE - Default return effect for methods returning Objective-C
  385. /// objects.
  386. RetEffect ObjCAllocRetE;
  387. /// ObjCInitRetE - Default return effect for init methods returning
  388. /// Objective-C objects.
  389. RetEffect ObjCInitRetE;
  390. /// SimpleSummaries - Used for uniquing summaries that don't have special
  391. /// effects.
  392. llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
  393. /// Create an OS object at +1.
  394. const RetainSummary *getOSSummaryCreateRule(const FunctionDecl *FD);
  395. /// Get an OS object at +0.
  396. const RetainSummary *getOSSummaryGetRule(const FunctionDecl *FD);
  397. /// Increment the reference count on OS object.
  398. const RetainSummary *getOSSummaryRetainRule(const FunctionDecl *FD);
  399. /// Decrement the reference count on OS object.
  400. const RetainSummary *getOSSummaryReleaseRule(const FunctionDecl *FD);
  401. /// Free the OS object.
  402. const RetainSummary *getOSSummaryFreeRule(const FunctionDecl *FD);
  403. const RetainSummary *getUnarySummary(const FunctionType* FT,
  404. ArgEffectKind AE);
  405. const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
  406. const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
  407. const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
  408. const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
  409. const RetainSummary *
  410. getPersistentSummary(RetEffect RetEff, ArgEffects ScratchArgs,
  411. ArgEffect ReceiverEff = ArgEffect(DoNothing),
  412. ArgEffect DefaultEff = ArgEffect(MayEscape),
  413. ArgEffect ThisEff = ArgEffect(DoNothing)) {
  414. RetainSummary Summ(ScratchArgs, RetEff, DefaultEff, ReceiverEff, ThisEff);
  415. return getPersistentSummary(Summ);
  416. }
  417. const RetainSummary *getDoNothingSummary() {
  418. return getPersistentSummary(RetEffect::MakeNoRet(),
  419. ArgEffects(AF.getEmptyMap()),
  420. ArgEffect(DoNothing), ArgEffect(DoNothing));
  421. }
  422. const RetainSummary *getDefaultSummary() {
  423. return getPersistentSummary(RetEffect::MakeNoRet(),
  424. ArgEffects(AF.getEmptyMap()),
  425. ArgEffect(DoNothing), ArgEffect(MayEscape));
  426. }
  427. const RetainSummary *getPersistentStopSummary() {
  428. return getPersistentSummary(
  429. RetEffect::MakeNoRet(), ArgEffects(AF.getEmptyMap()),
  430. ArgEffect(StopTracking), ArgEffect(StopTracking));
  431. }
  432. void InitializeClassMethodSummaries();
  433. void InitializeMethodSummaries();
  434. void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
  435. ObjCClassMethodSummaries[S] = Summ;
  436. }
  437. void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
  438. ObjCMethodSummaries[S] = Summ;
  439. }
  440. void addClassMethSummary(const char* Cls, const char* name,
  441. const RetainSummary *Summ, bool isNullary = true) {
  442. IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
  443. Selector S = isNullary ? GetNullarySelector(name, Ctx)
  444. : GetUnarySelector(name, Ctx);
  445. ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
  446. }
  447. void addInstMethSummary(const char* Cls, const char* nullaryName,
  448. const RetainSummary *Summ) {
  449. IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
  450. Selector S = GetNullarySelector(nullaryName, Ctx);
  451. ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
  452. }
  453. template <typename... Keywords>
  454. void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy &Summaries,
  455. const RetainSummary *Summ, Keywords *... Kws) {
  456. Selector S = getKeywordSelector(Ctx, Kws...);
  457. Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
  458. }
  459. template <typename... Keywords>
  460. void addInstMethSummary(const char *Cls, const RetainSummary *Summ,
  461. Keywords *... Kws) {
  462. addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, Kws...);
  463. }
  464. template <typename... Keywords>
  465. void addClsMethSummary(const char *Cls, const RetainSummary *Summ,
  466. Keywords *... Kws) {
  467. addMethodSummary(&Ctx.Idents.get(Cls), ObjCClassMethodSummaries, Summ,
  468. Kws...);
  469. }
  470. template <typename... Keywords>
  471. void addClsMethSummary(IdentifierInfo *II, const RetainSummary *Summ,
  472. Keywords *... Kws) {
  473. addMethodSummary(II, ObjCClassMethodSummaries, Summ, Kws...);
  474. }
  475. const RetainSummary * generateSummary(const FunctionDecl *FD,
  476. bool &AllowAnnotations);
  477. /// Return a summary for OSObject, or nullptr if not found.
  478. const RetainSummary *getSummaryForOSObject(const FunctionDecl *FD,
  479. StringRef FName, QualType RetTy);
  480. /// Return a summary for Objective-C or CF object, or nullptr if not found.
  481. const RetainSummary *getSummaryForObjCOrCFObject(
  482. const FunctionDecl *FD,
  483. StringRef FName,
  484. QualType RetTy,
  485. const FunctionType *FT,
  486. bool &AllowAnnotations);
  487. /// Apply the annotation of @c pd in function @c FD
  488. /// to the resulting summary stored in out-parameter @c Template.
  489. /// \return whether an annotation was applied.
  490. bool applyParamAnnotationEffect(const ParmVarDecl *pd, unsigned parm_idx,
  491. const NamedDecl *FD,
  492. RetainSummaryTemplate &Template);
  493. public:
  494. RetainSummaryManager(ASTContext &ctx, bool trackObjCAndCFObjects,
  495. bool trackOSObjects)
  496. : Ctx(ctx), ARCEnabled((bool)Ctx.getLangOpts().ObjCAutoRefCount),
  497. TrackObjCAndCFObjects(trackObjCAndCFObjects),
  498. TrackOSObjects(trackOSObjects), AF(BPAlloc),
  499. ObjCAllocRetE(ARCEnabled ? RetEffect::MakeNotOwned(ObjKind::ObjC)
  500. : RetEffect::MakeOwned(ObjKind::ObjC)),
  501. ObjCInitRetE(ARCEnabled ? RetEffect::MakeNotOwned(ObjKind::ObjC)
  502. : RetEffect::MakeOwnedWhenTrackedReceiver()) {
  503. InitializeClassMethodSummaries();
  504. InitializeMethodSummaries();
  505. }
  506. enum class BehaviorSummary {
  507. // Function does not return.
  508. NoOp,
  509. // Function returns the first argument.
  510. Identity,
  511. // Function returns "this" argument.
  512. IdentityThis,
  513. // Function either returns zero, or the input parameter.
  514. IdentityOrZero
  515. };
  516. std::optional<BehaviorSummary>
  517. canEval(const CallExpr *CE, const FunctionDecl *FD,
  518. bool &hasTrustedImplementationAnnotation);
  519. /// \return Whether the type corresponds to a known smart pointer
  520. /// implementation (that is, everything about it is inlineable).
  521. static bool isKnownSmartPointer(QualType QT);
  522. bool isTrustedReferenceCountImplementation(const Decl *FD);
  523. const RetainSummary *getSummary(AnyCall C,
  524. bool HasNonZeroCallbackArg=false,
  525. bool IsReceiverUnconsumedSelf=false,
  526. QualType ReceiverType={});
  527. RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
  528. private:
  529. /// getMethodSummary - This version of getMethodSummary is used to query
  530. /// the summary for the current method being analyzed.
  531. const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD);
  532. const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
  533. const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
  534. const ObjCMethodDecl *MD,
  535. QualType RetTy,
  536. ObjCMethodSummariesTy &CachedSummaries);
  537. const RetainSummary *
  538. getInstanceMethodSummary(const ObjCMessageExpr *ME, QualType ReceiverType);
  539. const RetainSummary *getClassMethodSummary(const ObjCMessageExpr *ME);
  540. const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
  541. Selector S, QualType RetTy);
  542. /// Determine if there is a special return effect for this function or method.
  543. std::optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
  544. const Decl *D);
  545. void updateSummaryFromAnnotations(const RetainSummary *&Summ,
  546. const ObjCMethodDecl *MD);
  547. void updateSummaryFromAnnotations(const RetainSummary *&Summ,
  548. const FunctionDecl *FD);
  549. const RetainSummary *updateSummaryForNonZeroCallbackArg(const RetainSummary *S,
  550. AnyCall &C);
  551. /// Special case '[super init];' and '[self init];'
  552. ///
  553. /// Even though calling '[super init]' without assigning the result to self
  554. /// and checking if the parent returns 'nil' is a bad pattern, it is common.
  555. /// Additionally, our Self Init checker already warns about it. To avoid
  556. /// overwhelming the user with messages from both checkers, we model the case
  557. /// of '[super init]' in cases when it is not consumed by another expression
  558. /// as if the call preserves the value of 'self'; essentially, assuming it can
  559. /// never fail and return 'nil'.
  560. /// Note, we don't want to just stop tracking the value since we want the
  561. /// RetainCount checker to report leaks and use-after-free if SelfInit checker
  562. /// is turned off.
  563. void updateSummaryForReceiverUnconsumedSelf(const RetainSummary *&S);
  564. /// Set argument types for arguments which are not doing anything.
  565. void updateSummaryForArgumentTypes(const AnyCall &C, const RetainSummary *&RS);
  566. /// Determine whether a declaration @c D of correspondent type (return
  567. /// type for functions/methods) @c QT has any of the given attributes,
  568. /// provided they pass necessary validation checks AND tracking the given
  569. /// attribute is enabled.
  570. /// Returns the object kind corresponding to the present attribute, or
  571. /// std::nullopt, if none of the specified attributes are present.
  572. /// Crashes if passed an attribute which is not explicitly handled.
  573. template <class T>
  574. std::optional<ObjKind> hasAnyEnabledAttrOf(const Decl *D, QualType QT);
  575. template <class T1, class T2, class... Others>
  576. std::optional<ObjKind> hasAnyEnabledAttrOf(const Decl *D, QualType QT);
  577. friend class RetainSummaryTemplate;
  578. };
  579. // Used to avoid allocating long-term (BPAlloc'd) memory for default retain
  580. // summaries. If a function or method looks like it has a default summary, but
  581. // it has annotations, the annotations are added to the stack-based template
  582. // and then copied into managed memory.
  583. class RetainSummaryTemplate {
  584. RetainSummaryManager &Manager;
  585. const RetainSummary *&RealSummary;
  586. RetainSummary ScratchSummary;
  587. bool Accessed;
  588. public:
  589. RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
  590. : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
  591. ~RetainSummaryTemplate() {
  592. if (Accessed)
  593. RealSummary = Manager.getPersistentSummary(ScratchSummary);
  594. }
  595. RetainSummary &operator*() {
  596. Accessed = true;
  597. return ScratchSummary;
  598. }
  599. RetainSummary *operator->() {
  600. Accessed = true;
  601. return &ScratchSummary;
  602. }
  603. };
  604. } // end namespace ento
  605. } // end namespace clang
  606. #endif
  607. #ifdef __GNUC__
  608. #pragma GCC diagnostic pop
  609. #endif