NSErrorChecker.cpp 11 KB

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