clang  15.0.0git
ObjCContainersChecker.cpp
Go to the documentation of this file.
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 
19 #include "clang/AST/ParentMap.h"
25 
26 using namespace clang;
27 using namespace ento;
28 
29 namespace {
30 class ObjCContainersChecker : public Checker< check::PreStmt<CallExpr>,
31  check::PostStmt<CallExpr>,
32  check::PointerEscape> {
33  mutable std::unique_ptr<BugType> BT;
34  inline void initBugType() const {
35  if (!BT)
36  BT.reset(new BugType(this, "CFArray API",
38  }
39 
40  inline SymbolRef getArraySym(const Expr *E, CheckerContext &C) const {
41  SVal ArrayRef = C.getSVal(E);
42  SymbolRef ArraySym = ArrayRef.getAsSymbol();
43  return ArraySym;
44  }
45 
46  void addSizeInfo(const Expr *Array, const Expr *Size,
47  CheckerContext &C) const;
48 
49 public:
50  void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
51  void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
52  ProgramStateRef checkPointerEscape(ProgramStateRef State,
53  const InvalidatedSymbols &Escaped,
54  const CallEvent *Call,
55  PointerEscapeKind Kind) const;
56 
57  void printState(raw_ostream &OS, ProgramStateRef State,
58  const char *NL, const char *Sep) const override;
59 };
60 } // end anonymous namespace
61 
62 // ProgramState trait - a map from array symbol to its state.
63 REGISTER_MAP_WITH_PROGRAMSTATE(ArraySizeMap, SymbolRef, DefinedSVal)
64 
65 void ObjCContainersChecker::addSizeInfo(const Expr *Array, const Expr *Size,
66  CheckerContext &C) const {
67  ProgramStateRef State = C.getState();
68  SVal SizeV = C.getSVal(Size);
69  // Undefined is reported by another checker.
70  if (SizeV.isUnknownOrUndef())
71  return;
72 
73  // Get the ArrayRef symbol.
74  SVal ArrayRef = C.getSVal(Array);
75  SymbolRef ArraySym = ArrayRef.getAsSymbol();
76  if (!ArraySym)
77  return;
78 
79  C.addTransition(
80  State->set<ArraySizeMap>(ArraySym, SizeV.castAs<DefinedSVal>()));
81 }
82 
83 void ObjCContainersChecker::checkPostStmt(const CallExpr *CE,
84  CheckerContext &C) const {
85  StringRef Name = C.getCalleeName(CE);
86  if (Name.empty() || CE->getNumArgs() < 1)
87  return;
88 
89  // Add array size information to the state.
90  if (Name.equals("CFArrayCreate")) {
91  if (CE->getNumArgs() < 3)
92  return;
93  // Note, we can visit the Create method in the post-visit because
94  // the CFIndex parameter is passed in by value and will not be invalidated
95  // by the call.
96  addSizeInfo(CE, CE->getArg(2), C);
97  return;
98  }
99 
100  if (Name.equals("CFArrayGetCount")) {
101  addSizeInfo(CE->getArg(0), CE, C);
102  return;
103  }
104 }
105 
106 void ObjCContainersChecker::checkPreStmt(const CallExpr *CE,
107  CheckerContext &C) const {
108  StringRef Name = C.getCalleeName(CE);
109  if (Name.empty() || CE->getNumArgs() < 2)
110  return;
111 
112  // Check the array access.
113  if (Name.equals("CFArrayGetValueAtIndex")) {
114  ProgramStateRef State = C.getState();
115  // Retrieve the size.
116  // Find out if we saw this array symbol before and have information about
117  // it.
118  const Expr *ArrayExpr = CE->getArg(0);
119  SymbolRef ArraySym = getArraySym(ArrayExpr, C);
120  if (!ArraySym)
121  return;
122 
123  const DefinedSVal *Size = State->get<ArraySizeMap>(ArraySym);
124 
125  if (!Size)
126  return;
127 
128  // Get the index.
129  const Expr *IdxExpr = CE->getArg(1);
130  SVal IdxVal = C.getSVal(IdxExpr);
131  if (IdxVal.isUnknownOrUndef())
132  return;
133  DefinedSVal Idx = IdxVal.castAs<DefinedSVal>();
134 
135  // Now, check if 'Idx in [0, Size-1]'.
136  const QualType T = IdxExpr->getType();
137  ProgramStateRef StInBound, StOutBound;
138  std::tie(StInBound, StOutBound) = State->assumeInBoundDual(Idx, *Size, T);
139  if (StOutBound && !StInBound) {
140  ExplodedNode *N = C.generateErrorNode(StOutBound);
141  if (!N)
142  return;
143  initBugType();
144  auto R = std::make_unique<PathSensitiveBugReport>(
145  *BT, "Index is out of bounds", N);
146  R->addRange(IdxExpr->getSourceRange());
147  bugreporter::trackExpressionValue(N, IdxExpr, *R,
149  /*EnableNullFPSuppression=*/false});
150  C.emitReport(std::move(R));
151  return;
152  }
153  }
154 }
155 
157 ObjCContainersChecker::checkPointerEscape(ProgramStateRef State,
158  const InvalidatedSymbols &Escaped,
159  const CallEvent *Call,
160  PointerEscapeKind Kind) const {
161  for (const auto &Sym : Escaped) {
162  // When a symbol for a mutable array escapes, we can't reason precisely
163  // about its size any more -- so remove it from the map.
164  // Note that we aren't notified here when a CFMutableArrayRef escapes as a
165  // CFArrayRef. This is because CFArrayRef is typedef'd as a pointer to a
166  // const-qualified type.
167  State = State->remove<ArraySizeMap>(Sym);
168  }
169  return State;
170 }
171 
172 void ObjCContainersChecker::printState(raw_ostream &OS, ProgramStateRef State,
173  const char *NL, const char *Sep) const {
174  ArraySizeMapTy Map = State->get<ArraySizeMap>();
175  if (Map.isEmpty())
176  return;
177 
178  OS << Sep << "ObjC container sizes :" << NL;
179  for (auto I : Map) {
180  OS << I.first << " : " << I.second << NL;
181  }
182 }
183 
184 /// Register checker.
185 void ento::registerObjCContainersChecker(CheckerManager &mgr) {
186  mgr.registerChecker<ObjCContainersChecker>();
187 }
188 
189 bool ento::shouldRegisterObjCContainersChecker(const CheckerManager &mgr) {
190  return true;
191 }
clang::Stmt::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:324
clang::ento::ProgramStateRef
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
Definition: ProgramState_Fwd.h:37
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:731
AttributeLangSupport::C
@ C
Definition: SemaDeclAttr.cpp:55
clang::ento::SymbolRef
const SymExpr * SymbolRef
Definition: SymExpr.h:111
REGISTER_MAP_WITH_PROGRAMSTATE
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
Definition: ProgramStateTrait.h:87
BuiltinCheckerRegistration.h
CheckerManager.h
clang::CallExpr::getArg
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2992
clang::ento::bugreporter::TrackingKind::Thorough
@ Thorough
Default tracking kind – specifies that as much information should be gathered about the tracked expre...
clang::ento::categories::CoreFoundationObjectiveC
const char *const CoreFoundationObjectiveC
Definition: CommonBugCategories.cpp:16
clang::ento::bugreporter::trackExpressionValue
bool trackExpressionValue(const ExplodedNode *N, const Expr *E, PathSensitiveBugReport &R, TrackingOptions Opts={})
Attempts to add visitors to track expression value back to its point of origin.
clang::syntax::NodeRole::Size
@ Size
BugType.h
clang::CallExpr::getNumArgs
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2979
llvm::ArrayRef
Definition: LLVM.h:34
State
LineState State
Definition: UnwrappedLineFormatter.cpp:1126
CheckerContext.h
clang::ObjCPropertyAttribute::Kind
Kind
Definition: DeclObjCCommon.h:22
Checker.h
ParentMap.h
clang
Definition: CalledOnceCheck.h:17
clang::Expr::getType
QualType getType() const
Definition: Expr.h:141
clang::ento::PointerEscapeKind
PointerEscapeKind
Describes the different reasons a pointer escapes during analysis.
Definition: CheckerManager.h:78
ProgramStateTrait.h
clang::Expr
This represents one expression.
Definition: Expr.h:109
clang::ento::InvalidatedSymbols
llvm::DenseSet< SymbolRef > InvalidatedSymbols
Definition: Store.h:51
clang::CallExpr
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2801
clang::ento::ObjKind::OS
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...