Clang Project

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