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