ObjCContainersChecker.cpp 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. //== ObjCContainersChecker.cpp - Path sensitive checker for CFArray *- 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. // Performs path sensitive checks of Core Foundation static containers like
  10. // CFArray.
  11. // 1) Check for buffer overflows:
  12. // In CFArrayGetArrayAtIndex( myArray, index), if the index is outside the
  13. // index space of theArray (0 to N-1 inclusive (where N is the count of
  14. // theArray), the behavior is undefined.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  18. #include "clang/AST/ParentMap.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. using namespace clang;
  25. using namespace ento;
  26. namespace {
  27. class ObjCContainersChecker : public Checker< check::PreStmt<CallExpr>,
  28. check::PostStmt<CallExpr>,
  29. check::PointerEscape> {
  30. mutable std::unique_ptr<BugType> BT;
  31. inline void initBugType() const {
  32. if (!BT)
  33. BT.reset(new BugType(this, "CFArray API",
  34. categories::CoreFoundationObjectiveC));
  35. }
  36. inline SymbolRef getArraySym(const Expr *E, CheckerContext &C) const {
  37. SVal ArrayRef = C.getSVal(E);
  38. SymbolRef ArraySym = ArrayRef.getAsSymbol();
  39. return ArraySym;
  40. }
  41. void addSizeInfo(const Expr *Array, const Expr *Size,
  42. CheckerContext &C) const;
  43. public:
  44. /// A tag to id this checker.
  45. static void *getTag() { static int Tag; return &Tag; }
  46. void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
  47. void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
  48. ProgramStateRef checkPointerEscape(ProgramStateRef State,
  49. const InvalidatedSymbols &Escaped,
  50. const CallEvent *Call,
  51. PointerEscapeKind Kind) const;
  52. void printState(raw_ostream &OS, ProgramStateRef State,
  53. const char *NL, const char *Sep) const override;
  54. };
  55. } // end anonymous namespace
  56. // ProgramState trait - a map from array symbol to its state.
  57. REGISTER_MAP_WITH_PROGRAMSTATE(ArraySizeMap, SymbolRef, DefinedSVal)
  58. void ObjCContainersChecker::addSizeInfo(const Expr *Array, const Expr *Size,
  59. CheckerContext &C) const {
  60. ProgramStateRef State = C.getState();
  61. SVal SizeV = C.getSVal(Size);
  62. // Undefined is reported by another checker.
  63. if (SizeV.isUnknownOrUndef())
  64. return;
  65. // Get the ArrayRef symbol.
  66. SVal ArrayRef = C.getSVal(Array);
  67. SymbolRef ArraySym = ArrayRef.getAsSymbol();
  68. if (!ArraySym)
  69. return;
  70. C.addTransition(
  71. State->set<ArraySizeMap>(ArraySym, SizeV.castAs<DefinedSVal>()));
  72. }
  73. void ObjCContainersChecker::checkPostStmt(const CallExpr *CE,
  74. CheckerContext &C) const {
  75. StringRef Name = C.getCalleeName(CE);
  76. if (Name.empty() || CE->getNumArgs() < 1)
  77. return;
  78. // Add array size information to the state.
  79. if (Name.equals("CFArrayCreate")) {
  80. if (CE->getNumArgs() < 3)
  81. return;
  82. // Note, we can visit the Create method in the post-visit because
  83. // the CFIndex parameter is passed in by value and will not be invalidated
  84. // by the call.
  85. addSizeInfo(CE, CE->getArg(2), C);
  86. return;
  87. }
  88. if (Name.equals("CFArrayGetCount")) {
  89. addSizeInfo(CE->getArg(0), CE, C);
  90. return;
  91. }
  92. }
  93. void ObjCContainersChecker::checkPreStmt(const CallExpr *CE,
  94. CheckerContext &C) const {
  95. StringRef Name = C.getCalleeName(CE);
  96. if (Name.empty() || CE->getNumArgs() < 2)
  97. return;
  98. // Check the array access.
  99. if (Name.equals("CFArrayGetValueAtIndex")) {
  100. ProgramStateRef State = C.getState();
  101. // Retrieve the size.
  102. // Find out if we saw this array symbol before and have information about
  103. // it.
  104. const Expr *ArrayExpr = CE->getArg(0);
  105. SymbolRef ArraySym = getArraySym(ArrayExpr, C);
  106. if (!ArraySym)
  107. return;
  108. const DefinedSVal *Size = State->get<ArraySizeMap>(ArraySym);
  109. if (!Size)
  110. return;
  111. // Get the index.
  112. const Expr *IdxExpr = CE->getArg(1);
  113. SVal IdxVal = C.getSVal(IdxExpr);
  114. if (IdxVal.isUnknownOrUndef())
  115. return;
  116. DefinedSVal Idx = IdxVal.castAs<DefinedSVal>();
  117. // Now, check if 'Idx in [0, Size-1]'.
  118. const QualType T = IdxExpr->getType();
  119. ProgramStateRef StInBound = State->assumeInBound(Idx, *Size, true, T);
  120. ProgramStateRef StOutBound = State->assumeInBound(Idx, *Size, false, T);
  121. if (StOutBound && !StInBound) {
  122. ExplodedNode *N = C.generateErrorNode(StOutBound);
  123. if (!N)
  124. return;
  125. initBugType();
  126. auto R = std::make_unique<PathSensitiveBugReport>(
  127. *BT, "Index is out of bounds", N);
  128. R->addRange(IdxExpr->getSourceRange());
  129. bugreporter::trackExpressionValue(N, IdxExpr, *R,
  130. {bugreporter::TrackingKind::Thorough,
  131. /*EnableNullFPSuppression=*/false});
  132. C.emitReport(std::move(R));
  133. return;
  134. }
  135. }
  136. }
  137. ProgramStateRef
  138. ObjCContainersChecker::checkPointerEscape(ProgramStateRef State,
  139. const InvalidatedSymbols &Escaped,
  140. const CallEvent *Call,
  141. PointerEscapeKind Kind) const {
  142. for (const auto &Sym : Escaped) {
  143. // When a symbol for a mutable array escapes, we can't reason precisely
  144. // about its size any more -- so remove it from the map.
  145. // Note that we aren't notified here when a CFMutableArrayRef escapes as a
  146. // CFArrayRef. This is because CFArrayRef is typedef'd as a pointer to a
  147. // const-qualified type.
  148. State = State->remove<ArraySizeMap>(Sym);
  149. }
  150. return State;
  151. }
  152. void ObjCContainersChecker::printState(raw_ostream &OS, ProgramStateRef State,
  153. const char *NL, const char *Sep) const {
  154. ArraySizeMapTy Map = State->get<ArraySizeMap>();
  155. if (Map.isEmpty())
  156. return;
  157. OS << Sep << "ObjC container sizes :" << NL;
  158. for (auto I : Map) {
  159. OS << I.first << " : " << I.second << NL;
  160. }
  161. }
  162. /// Register checker.
  163. void ento::registerObjCContainersChecker(CheckerManager &mgr) {
  164. mgr.registerChecker<ObjCContainersChecker>();
  165. }
  166. bool ento::shouldRegisterObjCContainersChecker(const CheckerManager &mgr) {
  167. return true;
  168. }