NSErrorChecker.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. //=- NSErrorChecker.cpp - Coding conventions for uses of NSError -*- C++ -*-==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines a CheckNSError, a flow-insenstive check
  11. // that determines if an Objective-C class interface correctly returns
  12. // a non-void return type.
  13. //
  14. // File under feature request PR 2600.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "ClangSACheckers.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  21. #include "clang/StaticAnalyzer/Core/Checker.h"
  22. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  23. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  24. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  25. #include "llvm/ADT/SmallString.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. using namespace clang;
  28. using namespace ento;
  29. static bool IsNSError(QualType T, IdentifierInfo *II);
  30. static bool IsCFError(QualType T, IdentifierInfo *II);
  31. //===----------------------------------------------------------------------===//
  32. // NSErrorMethodChecker
  33. //===----------------------------------------------------------------------===//
  34. namespace {
  35. class NSErrorMethodChecker
  36. : public Checker< check::ASTDecl<ObjCMethodDecl> > {
  37. mutable IdentifierInfo *II;
  38. public:
  39. NSErrorMethodChecker() : II(nullptr) {}
  40. void checkASTDecl(const ObjCMethodDecl *D,
  41. AnalysisManager &mgr, BugReporter &BR) const;
  42. };
  43. }
  44. void NSErrorMethodChecker::checkASTDecl(const ObjCMethodDecl *D,
  45. AnalysisManager &mgr,
  46. BugReporter &BR) const {
  47. if (!D->isThisDeclarationADefinition())
  48. return;
  49. if (!D->getReturnType()->isVoidType())
  50. return;
  51. if (!II)
  52. II = &D->getASTContext().Idents.get("NSError");
  53. bool hasNSError = false;
  54. for (const auto *I : D->params()) {
  55. if (IsNSError(I->getType(), II)) {
  56. hasNSError = true;
  57. break;
  58. }
  59. }
  60. if (hasNSError) {
  61. const char *err = "Method accepting NSError** "
  62. "should have a non-void return value to indicate whether or not an "
  63. "error occurred";
  64. PathDiagnosticLocation L =
  65. PathDiagnosticLocation::create(D, BR.getSourceManager());
  66. BR.EmitBasicReport(D, this, "Bad return type when passing NSError**",
  67. "Coding conventions (Apple)", err, L);
  68. }
  69. }
  70. //===----------------------------------------------------------------------===//
  71. // CFErrorFunctionChecker
  72. //===----------------------------------------------------------------------===//
  73. namespace {
  74. class CFErrorFunctionChecker
  75. : public Checker< check::ASTDecl<FunctionDecl> > {
  76. mutable IdentifierInfo *II;
  77. public:
  78. CFErrorFunctionChecker() : II(nullptr) {}
  79. void checkASTDecl(const FunctionDecl *D,
  80. AnalysisManager &mgr, BugReporter &BR) const;
  81. };
  82. }
  83. void CFErrorFunctionChecker::checkASTDecl(const FunctionDecl *D,
  84. AnalysisManager &mgr,
  85. BugReporter &BR) const {
  86. if (!D->doesThisDeclarationHaveABody())
  87. return;
  88. if (!D->getReturnType()->isVoidType())
  89. return;
  90. if (!II)
  91. II = &D->getASTContext().Idents.get("CFErrorRef");
  92. bool hasCFError = false;
  93. for (auto I : D->params()) {
  94. if (IsCFError(I->getType(), II)) {
  95. hasCFError = true;
  96. break;
  97. }
  98. }
  99. if (hasCFError) {
  100. const char *err = "Function accepting CFErrorRef* "
  101. "should have a non-void return value to indicate whether or not an "
  102. "error occurred";
  103. PathDiagnosticLocation L =
  104. PathDiagnosticLocation::create(D, BR.getSourceManager());
  105. BR.EmitBasicReport(D, this, "Bad return type when passing CFErrorRef*",
  106. "Coding conventions (Apple)", err, L);
  107. }
  108. }
  109. //===----------------------------------------------------------------------===//
  110. // NSOrCFErrorDerefChecker
  111. //===----------------------------------------------------------------------===//
  112. namespace {
  113. class NSErrorDerefBug : public BugType {
  114. public:
  115. NSErrorDerefBug(const CheckerBase *Checker)
  116. : BugType(Checker, "NSError** null dereference",
  117. "Coding conventions (Apple)") {}
  118. };
  119. class CFErrorDerefBug : public BugType {
  120. public:
  121. CFErrorDerefBug(const CheckerBase *Checker)
  122. : BugType(Checker, "CFErrorRef* null dereference",
  123. "Coding conventions (Apple)") {}
  124. };
  125. }
  126. namespace {
  127. class NSOrCFErrorDerefChecker
  128. : public Checker< check::Location,
  129. check::Event<ImplicitNullDerefEvent> > {
  130. mutable IdentifierInfo *NSErrorII, *CFErrorII;
  131. mutable std::unique_ptr<NSErrorDerefBug> NSBT;
  132. mutable std::unique_ptr<CFErrorDerefBug> CFBT;
  133. public:
  134. bool ShouldCheckNSError, ShouldCheckCFError;
  135. NSOrCFErrorDerefChecker() : NSErrorII(nullptr), CFErrorII(nullptr),
  136. ShouldCheckNSError(0), ShouldCheckCFError(0) { }
  137. void checkLocation(SVal loc, bool isLoad, const Stmt *S,
  138. CheckerContext &C) const;
  139. void checkEvent(ImplicitNullDerefEvent event) const;
  140. };
  141. }
  142. typedef llvm::ImmutableMap<SymbolRef, unsigned> ErrorOutFlag;
  143. REGISTER_TRAIT_WITH_PROGRAMSTATE(NSErrorOut, ErrorOutFlag)
  144. REGISTER_TRAIT_WITH_PROGRAMSTATE(CFErrorOut, ErrorOutFlag)
  145. template <typename T>
  146. static bool hasFlag(SVal val, ProgramStateRef state) {
  147. if (SymbolRef sym = val.getAsSymbol())
  148. if (const unsigned *attachedFlags = state->get<T>(sym))
  149. return *attachedFlags;
  150. return false;
  151. }
  152. template <typename T>
  153. static void setFlag(ProgramStateRef state, SVal val, CheckerContext &C) {
  154. // We tag the symbol that the SVal wraps.
  155. if (SymbolRef sym = val.getAsSymbol())
  156. C.addTransition(state->set<T>(sym, true));
  157. }
  158. static QualType parameterTypeFromSVal(SVal val, CheckerContext &C) {
  159. const StackFrameContext *
  160. SFC = C.getLocationContext()->getCurrentStackFrame();
  161. if (Optional<loc::MemRegionVal> X = val.getAs<loc::MemRegionVal>()) {
  162. const MemRegion* R = X->getRegion();
  163. if (const VarRegion *VR = R->getAs<VarRegion>())
  164. if (const StackArgumentsSpaceRegion *
  165. stackReg = dyn_cast<StackArgumentsSpaceRegion>(VR->getMemorySpace()))
  166. if (stackReg->getStackFrame() == SFC)
  167. return VR->getValueType();
  168. }
  169. return QualType();
  170. }
  171. void NSOrCFErrorDerefChecker::checkLocation(SVal loc, bool isLoad,
  172. const Stmt *S,
  173. CheckerContext &C) const {
  174. if (!isLoad)
  175. return;
  176. if (loc.isUndef() || !loc.getAs<Loc>())
  177. return;
  178. ASTContext &Ctx = C.getASTContext();
  179. ProgramStateRef state = C.getState();
  180. // If we are loading from NSError**/CFErrorRef* parameter, mark the resulting
  181. // SVal so that we can later check it when handling the
  182. // ImplicitNullDerefEvent event.
  183. // FIXME: Cumbersome! Maybe add hook at construction of SVals at start of
  184. // function ?
  185. QualType parmT = parameterTypeFromSVal(loc, C);
  186. if (parmT.isNull())
  187. return;
  188. if (!NSErrorII)
  189. NSErrorII = &Ctx.Idents.get("NSError");
  190. if (!CFErrorII)
  191. CFErrorII = &Ctx.Idents.get("CFErrorRef");
  192. if (ShouldCheckNSError && IsNSError(parmT, NSErrorII)) {
  193. setFlag<NSErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
  194. return;
  195. }
  196. if (ShouldCheckCFError && IsCFError(parmT, CFErrorII)) {
  197. setFlag<CFErrorOut>(state, state->getSVal(loc.castAs<Loc>()), C);
  198. return;
  199. }
  200. }
  201. void NSOrCFErrorDerefChecker::checkEvent(ImplicitNullDerefEvent event) const {
  202. if (event.IsLoad)
  203. return;
  204. SVal loc = event.Location;
  205. ProgramStateRef state = event.SinkNode->getState();
  206. BugReporter &BR = *event.BR;
  207. bool isNSError = hasFlag<NSErrorOut>(loc, state);
  208. bool isCFError = false;
  209. if (!isNSError)
  210. isCFError = hasFlag<CFErrorOut>(loc, state);
  211. if (!(isNSError || isCFError))
  212. return;
  213. // Storing to possible null NSError/CFErrorRef out parameter.
  214. SmallString<128> Buf;
  215. llvm::raw_svector_ostream os(Buf);
  216. os << "Potential null dereference. According to coding standards ";
  217. os << (isNSError
  218. ? "in 'Creating and Returning NSError Objects' the parameter"
  219. : "documented in CoreFoundation/CFError.h the parameter");
  220. os << " may be null";
  221. BugType *bug = nullptr;
  222. if (isNSError) {
  223. if (!NSBT)
  224. NSBT.reset(new NSErrorDerefBug(this));
  225. bug = NSBT.get();
  226. }
  227. else {
  228. if (!CFBT)
  229. CFBT.reset(new CFErrorDerefBug(this));
  230. bug = CFBT.get();
  231. }
  232. BR.emitReport(llvm::make_unique<BugReport>(*bug, os.str(), event.SinkNode));
  233. }
  234. static bool IsNSError(QualType T, IdentifierInfo *II) {
  235. const PointerType* PPT = T->getAs<PointerType>();
  236. if (!PPT)
  237. return false;
  238. const ObjCObjectPointerType* PT =
  239. PPT->getPointeeType()->getAs<ObjCObjectPointerType>();
  240. if (!PT)
  241. return false;
  242. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  243. // FIXME: Can ID ever be NULL?
  244. if (ID)
  245. return II == ID->getIdentifier();
  246. return false;
  247. }
  248. static bool IsCFError(QualType T, IdentifierInfo *II) {
  249. const PointerType* PPT = T->getAs<PointerType>();
  250. if (!PPT) return false;
  251. const TypedefType* TT = PPT->getPointeeType()->getAs<TypedefType>();
  252. if (!TT) return false;
  253. return TT->getDecl()->getIdentifier() == II;
  254. }
  255. void ento::registerNSErrorChecker(CheckerManager &mgr) {
  256. mgr.registerChecker<NSErrorMethodChecker>();
  257. NSOrCFErrorDerefChecker *checker =
  258. mgr.registerChecker<NSOrCFErrorDerefChecker>();
  259. checker->ShouldCheckNSError = true;
  260. }
  261. void ento::registerCFErrorChecker(CheckerManager &mgr) {
  262. mgr.registerChecker<CFErrorFunctionChecker>();
  263. NSOrCFErrorDerefChecker *checker =
  264. mgr.registerChecker<NSOrCFErrorDerefChecker>();
  265. checker->ShouldCheckCFError = true;
  266. }