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 
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",
37                            categories::CoreFoundationObjectiveC));
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   /// A tag to id this checker.
51   static void *getTag() { static int Tag; return &Tag; }
52 
53   void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
54   void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
55   ProgramStateRef checkPointerEscape(ProgramStateRef State,
56                                      const InvalidatedSymbols &Escaped,
57                                      const CallEvent *Call,
58                                      PointerEscapeKind Kind) const;
59 
60   void printState(raw_ostream &OS, ProgramStateRef State,
61                   const char *NL, const char *Sep) const override;
62 };
63 } // end anonymous namespace
64 
65 // ProgramState trait - a map from array symbol to its state.
66 REGISTER_MAP_WITH_PROGRAMSTATE(ArraySizeMap, SymbolRef, DefinedSVal)
67 
68 void ObjCContainersChecker::addSizeInfo(const Expr *Array, const Expr *Size,
69                                         CheckerContext &C) const {
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 
86 void ObjCContainersChecker::checkPostStmt(const CallExpr *CE,
87                                           CheckerContext &C) const {
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(CE, CE->getArg(2), C);
100     return;
101   }
102 
103   if (Name.equals("CFArrayGetCount")) {
104     addSizeInfo(CE->getArg(0), CE, C);
105     return;
106   }
107 }
108 
109 void ObjCContainersChecker::checkPreStmt(const CallExpr *CE,
110                                          CheckerContext &C) const {
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(ArrayExpr, C);
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 = std::make_unique<PathSensitiveBugReport>(
148           *BT, "Index is out of bounds", N);
149       R->addRange(IdxExpr->getSourceRange());
150       bugreporter::trackExpressionValue(N, IdxExpr, *R,
151                                         {bugreporter::TrackingKind::Thorough,
152                                          /*EnableNullFPSuppression=*/false});
153       C.emitReport(std::move(R));
154       return;
155     }
156   }
157 }
158 
159 ProgramStateRef
160 ObjCContainersChecker::checkPointerEscape(ProgramStateRef State,
161                                           const InvalidatedSymbols &Escaped,
162                                           const CallEvent *Call,
163                                           PointerEscapeKind Kind) const {
164   for (const auto &Sym : Escaped) {
165     // When a symbol for a mutable array escapes, we can't reason precisely
166     // about its size any more -- so remove it from the map.
167     // Note that we aren't notified here when a CFMutableArrayRef escapes as a
168     // CFArrayRef. This is because CFArrayRef is typedef'd as a pointer to a
169     // const-qualified type.
170     State = State->remove<ArraySizeMap>(Sym);
171   }
172   return State;
173 }
174 
175 void ObjCContainersChecker::printState(raw_ostream &OS, ProgramStateRef State,
176                                        const char *NL, const char *Sep) const {
177   ArraySizeMapTy Map = State->get<ArraySizeMap>();
178   if (Map.isEmpty())
179     return;
180 
181   OS << Sep << "ObjC container sizes :" << NL;
182   for (auto I : Map) {
183     OS << I.first << " : " << I.second << NL;
184   }
185 }
186 
187 /// Register checker.
188 void ento::registerObjCContainersChecker(CheckerManager &mgr) {
189   mgr.registerChecker<ObjCContainersChecker>();
190 }
191 
192 bool ento::shouldRegisterObjCContainersChecker(const CheckerManager &mgr) {
193   return true;
194 }
195