ObjCMissingSuperCallChecker.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. //==- ObjCMissingSuperCallChecker.cpp - Check missing super-calls in ObjC --==//
  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 a ObjCMissingSuperCallChecker, a checker that
  10. // analyzes a UIViewController implementation to determine if it
  11. // correctly calls super in the methods where this is mandatory.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  15. #include "clang/Analysis/PathDiagnostic.h"
  16. #include "clang/AST/DeclObjC.h"
  17. #include "clang/AST/Expr.h"
  18. #include "clang/AST/ExprObjC.h"
  19. #include "clang/AST/RecursiveASTVisitor.h"
  20. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  21. #include "clang/StaticAnalyzer/Core/Checker.h"
  22. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/ADT/SmallString.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. using namespace clang;
  27. using namespace ento;
  28. namespace {
  29. struct SelectorDescriptor {
  30. const char *SelectorName;
  31. unsigned ArgumentCount;
  32. };
  33. //===----------------------------------------------------------------------===//
  34. // FindSuperCallVisitor - Identify specific calls to the superclass.
  35. //===----------------------------------------------------------------------===//
  36. class FindSuperCallVisitor : public RecursiveASTVisitor<FindSuperCallVisitor> {
  37. public:
  38. explicit FindSuperCallVisitor(Selector S) : DoesCallSuper(false), Sel(S) {}
  39. bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
  40. if (E->getSelector() == Sel)
  41. if (E->getReceiverKind() == ObjCMessageExpr::SuperInstance)
  42. DoesCallSuper = true;
  43. // Recurse if we didn't find the super call yet.
  44. return !DoesCallSuper;
  45. }
  46. bool DoesCallSuper;
  47. private:
  48. Selector Sel;
  49. };
  50. //===----------------------------------------------------------------------===//
  51. // ObjCSuperCallChecker
  52. //===----------------------------------------------------------------------===//
  53. class ObjCSuperCallChecker : public Checker<
  54. check::ASTDecl<ObjCImplementationDecl> > {
  55. public:
  56. ObjCSuperCallChecker() : IsInitialized(false) {}
  57. void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager &Mgr,
  58. BugReporter &BR) const;
  59. private:
  60. bool isCheckableClass(const ObjCImplementationDecl *D,
  61. StringRef &SuperclassName) const;
  62. void initializeSelectors(ASTContext &Ctx) const;
  63. void fillSelectors(ASTContext &Ctx, ArrayRef<SelectorDescriptor> Sel,
  64. StringRef ClassName) const;
  65. mutable llvm::StringMap<llvm::SmallPtrSet<Selector, 16>> SelectorsForClass;
  66. mutable bool IsInitialized;
  67. };
  68. }
  69. /// Determine whether the given class has a superclass that we want
  70. /// to check. The name of the found superclass is stored in SuperclassName.
  71. ///
  72. /// \param D The declaration to check for superclasses.
  73. /// \param[out] SuperclassName On return, the found superclass name.
  74. bool ObjCSuperCallChecker::isCheckableClass(const ObjCImplementationDecl *D,
  75. StringRef &SuperclassName) const {
  76. const ObjCInterfaceDecl *ID = D->getClassInterface()->getSuperClass();
  77. for ( ; ID ; ID = ID->getSuperClass())
  78. {
  79. SuperclassName = ID->getIdentifier()->getName();
  80. if (SelectorsForClass.count(SuperclassName))
  81. return true;
  82. }
  83. return false;
  84. }
  85. void ObjCSuperCallChecker::fillSelectors(ASTContext &Ctx,
  86. ArrayRef<SelectorDescriptor> Sel,
  87. StringRef ClassName) const {
  88. llvm::SmallPtrSet<Selector, 16> &ClassSelectors =
  89. SelectorsForClass[ClassName];
  90. // Fill the Selectors SmallSet with all selectors we want to check.
  91. for (ArrayRef<SelectorDescriptor>::iterator I = Sel.begin(), E = Sel.end();
  92. I != E; ++I) {
  93. SelectorDescriptor Descriptor = *I;
  94. assert(Descriptor.ArgumentCount <= 1); // No multi-argument selectors yet.
  95. // Get the selector.
  96. IdentifierInfo *II = &Ctx.Idents.get(Descriptor.SelectorName);
  97. Selector Sel = Ctx.Selectors.getSelector(Descriptor.ArgumentCount, &II);
  98. ClassSelectors.insert(Sel);
  99. }
  100. }
  101. void ObjCSuperCallChecker::initializeSelectors(ASTContext &Ctx) const {
  102. { // Initialize selectors for: UIViewController
  103. const SelectorDescriptor Selectors[] = {
  104. { "addChildViewController", 1 },
  105. { "viewDidAppear", 1 },
  106. { "viewDidDisappear", 1 },
  107. { "viewWillAppear", 1 },
  108. { "viewWillDisappear", 1 },
  109. { "removeFromParentViewController", 0 },
  110. { "didReceiveMemoryWarning", 0 },
  111. { "viewDidUnload", 0 },
  112. { "viewDidLoad", 0 },
  113. { "viewWillUnload", 0 },
  114. { "updateViewConstraints", 0 },
  115. { "encodeRestorableStateWithCoder", 1 },
  116. { "restoreStateWithCoder", 1 }};
  117. fillSelectors(Ctx, Selectors, "UIViewController");
  118. }
  119. { // Initialize selectors for: UIResponder
  120. const SelectorDescriptor Selectors[] = {
  121. { "resignFirstResponder", 0 }};
  122. fillSelectors(Ctx, Selectors, "UIResponder");
  123. }
  124. { // Initialize selectors for: NSResponder
  125. const SelectorDescriptor Selectors[] = {
  126. { "encodeRestorableStateWithCoder", 1 },
  127. { "restoreStateWithCoder", 1 }};
  128. fillSelectors(Ctx, Selectors, "NSResponder");
  129. }
  130. { // Initialize selectors for: NSDocument
  131. const SelectorDescriptor Selectors[] = {
  132. { "encodeRestorableStateWithCoder", 1 },
  133. { "restoreStateWithCoder", 1 }};
  134. fillSelectors(Ctx, Selectors, "NSDocument");
  135. }
  136. IsInitialized = true;
  137. }
  138. void ObjCSuperCallChecker::checkASTDecl(const ObjCImplementationDecl *D,
  139. AnalysisManager &Mgr,
  140. BugReporter &BR) const {
  141. ASTContext &Ctx = BR.getContext();
  142. // We need to initialize the selector table once.
  143. if (!IsInitialized)
  144. initializeSelectors(Ctx);
  145. // Find out whether this class has a superclass that we are supposed to check.
  146. StringRef SuperclassName;
  147. if (!isCheckableClass(D, SuperclassName))
  148. return;
  149. // Iterate over all instance methods.
  150. for (auto *MD : D->instance_methods()) {
  151. Selector S = MD->getSelector();
  152. // Find out whether this is a selector that we want to check.
  153. if (!SelectorsForClass[SuperclassName].count(S))
  154. continue;
  155. // Check if the method calls its superclass implementation.
  156. if (MD->getBody())
  157. {
  158. FindSuperCallVisitor Visitor(S);
  159. Visitor.TraverseDecl(MD);
  160. // It doesn't call super, emit a diagnostic.
  161. if (!Visitor.DoesCallSuper) {
  162. PathDiagnosticLocation DLoc =
  163. PathDiagnosticLocation::createEnd(MD->getBody(),
  164. BR.getSourceManager(),
  165. Mgr.getAnalysisDeclContext(D));
  166. const char *Name = "Missing call to superclass";
  167. SmallString<320> Buf;
  168. llvm::raw_svector_ostream os(Buf);
  169. os << "The '" << S.getAsString()
  170. << "' instance method in " << SuperclassName.str() << " subclass '"
  171. << *D << "' is missing a [super " << S.getAsString() << "] call";
  172. BR.EmitBasicReport(MD, this, Name, categories::CoreFoundationObjectiveC,
  173. os.str(), DLoc);
  174. }
  175. }
  176. }
  177. }
  178. //===----------------------------------------------------------------------===//
  179. // Check registration.
  180. //===----------------------------------------------------------------------===//
  181. void ento::registerObjCSuperCallChecker(CheckerManager &Mgr) {
  182. Mgr.registerChecker<ObjCSuperCallChecker>();
  183. }
  184. bool ento::shouldRegisterObjCSuperCallChecker(const CheckerManager &mgr) {
  185. return true;
  186. }
  187. /*
  188. ToDo list for expanding this check in the future, the list is not exhaustive.
  189. There are also cases where calling super is suggested but not "mandatory".
  190. In addition to be able to check the classes and methods below, architectural
  191. improvements like being able to allow for the super-call to be done in a called
  192. method would be good too.
  193. UIDocument subclasses
  194. - finishedHandlingError:recovered: (is multi-arg)
  195. - finishedHandlingError:recovered: (is multi-arg)
  196. UIViewController subclasses
  197. - loadView (should *never* call super)
  198. - transitionFromViewController:toViewController:
  199. duration:options:animations:completion: (is multi-arg)
  200. UICollectionViewController subclasses
  201. - loadView (take care because UIViewController subclasses should NOT call super
  202. in loadView, but UICollectionViewController subclasses should)
  203. NSObject subclasses
  204. - doesNotRecognizeSelector (it only has to call super if it doesn't throw)
  205. UIPopoverBackgroundView subclasses (some of those are class methods)
  206. - arrowDirection (should *never* call super)
  207. - arrowOffset (should *never* call super)
  208. - arrowBase (should *never* call super)
  209. - arrowHeight (should *never* call super)
  210. - contentViewInsets (should *never* call super)
  211. UITextSelectionRect subclasses (some of those are properties)
  212. - rect (should *never* call super)
  213. - range (should *never* call super)
  214. - writingDirection (should *never* call super)
  215. - isVertical (should *never* call super)
  216. - containsStart (should *never* call super)
  217. - containsEnd (should *never* call super)
  218. */