xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp (revision 8c22cbea87beb74da3dc5891c40cdf574cd5fe56)
1 //== ArrayBoundCheckerV2.cpp ------------------------------------*- 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 // This file defines ArrayBoundCheckerV2, which is a path-sensitive check
10 // which looks for an out-of-bound array element access.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/CharUnits.h"
15 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
16 #include "clang/StaticAnalyzer/Checkers/Taint.h"
17 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18 #include "clang/StaticAnalyzer/Core/Checker.h"
19 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <optional>
27 
28 using namespace clang;
29 using namespace ento;
30 using namespace taint;
31 
32 namespace {
33 class ArrayBoundCheckerV2 :
34     public Checker<check::Location> {
35   mutable std::unique_ptr<BuiltinBug> BT;
36   mutable std::unique_ptr<BugType> TaintBT;
37 
38   enum OOB_Kind { OOB_Precedes, OOB_Excedes };
39 
40   void reportOOB(CheckerContext &C, ProgramStateRef errorState,
41                  OOB_Kind kind) const;
42   void reportTaintOOB(CheckerContext &C, ProgramStateRef errorState,
43                       SVal TaintedSVal) const;
44 
45   static bool isFromCtypeMacro(const Stmt *S, ASTContext &AC);
46 
47 public:
48   void checkLocation(SVal l, bool isLoad, const Stmt *S,
49                      CheckerContext &C) const;
50 };
51 
52 // FIXME: Eventually replace RegionRawOffset with this class.
53 class RegionRawOffsetV2 {
54 private:
55   const SubRegion *baseRegion;
56   SVal byteOffset;
57 
58   RegionRawOffsetV2()
59     : baseRegion(nullptr), byteOffset(UnknownVal()) {}
60 
61 public:
62   RegionRawOffsetV2(const SubRegion *base, NonLoc offset)
63       : baseRegion(base), byteOffset(offset) { assert(base); }
64 
65   NonLoc getByteOffset() const { return byteOffset.castAs<NonLoc>(); }
66   const SubRegion *getRegion() const { return baseRegion; }
67 
68   static RegionRawOffsetV2 computeOffset(ProgramStateRef state,
69                                          SValBuilder &svalBuilder,
70                                          SVal location);
71 
72   void dump() const;
73   void dumpToStream(raw_ostream &os) const;
74 };
75 }
76 
77 // TODO: once the constraint manager is smart enough to handle non simplified
78 // symbolic expressions remove this function. Note that this can not be used in
79 // the constraint manager as is, since this does not handle overflows. It is
80 // safe to assume, however, that memory offsets will not overflow.
81 // NOTE: callers of this function need to be aware of the effects of overflows
82 // and signed<->unsigned conversions!
83 static std::pair<NonLoc, nonloc::ConcreteInt>
84 getSimplifiedOffsets(NonLoc offset, nonloc::ConcreteInt extent,
85                      SValBuilder &svalBuilder) {
86   std::optional<nonloc::SymbolVal> SymVal = offset.getAs<nonloc::SymbolVal>();
87   if (SymVal && SymVal->isExpression()) {
88     if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SymVal->getSymbol())) {
89       llvm::APSInt constant =
90           APSIntType(extent.getValue()).convert(SIE->getRHS());
91       switch (SIE->getOpcode()) {
92       case BO_Mul:
93         // The constant should never be 0 here, since it the result of scaling
94         // based on the size of a type which is never 0.
95         if ((extent.getValue() % constant) != 0)
96           return std::pair<NonLoc, nonloc::ConcreteInt>(offset, extent);
97         else
98           return getSimplifiedOffsets(
99               nonloc::SymbolVal(SIE->getLHS()),
100               svalBuilder.makeIntVal(extent.getValue() / constant),
101               svalBuilder);
102       case BO_Add:
103         return getSimplifiedOffsets(
104             nonloc::SymbolVal(SIE->getLHS()),
105             svalBuilder.makeIntVal(extent.getValue() - constant), svalBuilder);
106       default:
107         break;
108       }
109     }
110   }
111 
112   return std::pair<NonLoc, nonloc::ConcreteInt>(offset, extent);
113 }
114 
115 // Evaluate the comparison Value < Threshold with the help of the custom
116 // simplification algorithm defined for this checker. Return a pair of states,
117 // where the first one corresponds to "value below threshold" and the second
118 // corresponds to "value at or above threshold". Returns {nullptr, nullptr} in
119 // the case when the evaluation fails.
120 static std::pair<ProgramStateRef, ProgramStateRef>
121 compareValueToThreshold(ProgramStateRef State, NonLoc Value, NonLoc Threshold,
122                         SValBuilder &SVB) {
123   if (auto ConcreteThreshold = Threshold.getAs<nonloc::ConcreteInt>()) {
124     std::tie(Value, Threshold) = getSimplifiedOffsets(Value, *ConcreteThreshold, SVB);
125   }
126   if (auto ConcreteThreshold = Threshold.getAs<nonloc::ConcreteInt>()) {
127     QualType T = Value.getType(SVB.getContext());
128     if (T->isUnsignedIntegerType() && ConcreteThreshold->getValue().isNegative()) {
129       // In this case we reduced the bound check to a comparison of the form
130       //   (symbol or value with unsigned type) < (negative number)
131       // which is always false. We are handling these cases separately because
132       // evalBinOpNN can perform a signed->unsigned conversion that turns the
133       // negative number into a huge positive value and leads to wildly
134       // inaccurate conclusions.
135       return {nullptr, State};
136     }
137   }
138   auto BelowThreshold =
139       SVB.evalBinOpNN(State, BO_LT, Value, Threshold, SVB.getConditionType()).getAs<NonLoc>();
140 
141   if (BelowThreshold)
142     return State->assume(*BelowThreshold);
143 
144   return {nullptr, nullptr};
145 }
146 
147 void ArrayBoundCheckerV2::checkLocation(SVal location, bool isLoad,
148                                         const Stmt* LoadS,
149                                         CheckerContext &checkerContext) const {
150 
151   // NOTE: Instead of using ProgramState::assumeInBound(), we are prototyping
152   // some new logic here that reasons directly about memory region extents.
153   // Once that logic is more mature, we can bring it back to assumeInBound()
154   // for all clients to use.
155   //
156   // The algorithm we are using here for bounds checking is to see if the
157   // memory access is within the extent of the base region.  Since we
158   // have some flexibility in defining the base region, we can achieve
159   // various levels of conservatism in our buffer overflow checking.
160 
161   // The header ctype.h (from e.g. glibc) implements the isXXXXX() macros as
162   //   #define isXXXXX(arg) (LOOKUP_TABLE[arg] & BITMASK_FOR_XXXXX)
163   // and incomplete analysis of these leads to false positives. As even
164   // accurate reports would be confusing for the users, just disable reports
165   // from these macros:
166   if (isFromCtypeMacro(LoadS, checkerContext.getASTContext()))
167     return;
168 
169   ProgramStateRef state = checkerContext.getState();
170 
171   SValBuilder &svalBuilder = checkerContext.getSValBuilder();
172   const RegionRawOffsetV2 &rawOffset =
173     RegionRawOffsetV2::computeOffset(state, svalBuilder, location);
174 
175   if (!rawOffset.getRegion())
176     return;
177 
178   NonLoc ByteOffset = rawOffset.getByteOffset();
179 
180   // CHECK LOWER BOUND
181   const MemSpaceRegion *SR = rawOffset.getRegion()->getMemorySpace();
182   if (!llvm::isa<UnknownSpaceRegion>(SR)) {
183     // A pointer to UnknownSpaceRegion may point to the middle of
184     // an allocated region.
185 
186     auto [state_precedesLowerBound, state_withinLowerBound] =
187         compareValueToThreshold(state, ByteOffset,
188                                 svalBuilder.makeZeroArrayIndex(), svalBuilder);
189 
190     if (state_precedesLowerBound && !state_withinLowerBound) {
191       // We know that the index definitely precedes the lower bound.
192       reportOOB(checkerContext, state_precedesLowerBound, OOB_Precedes);
193       return;
194     }
195 
196     if (state_withinLowerBound)
197       state = state_withinLowerBound;
198   }
199 
200   // CHECK UPPER BOUND
201   DefinedOrUnknownSVal Size =
202       getDynamicExtent(state, rawOffset.getRegion(), svalBuilder);
203   if (auto KnownSize = Size.getAs<NonLoc>()) {
204     auto [state_withinUpperBound, state_exceedsUpperBound] =
205         compareValueToThreshold(state, ByteOffset, *KnownSize, svalBuilder);
206 
207     if (state_exceedsUpperBound) {
208       if (!state_withinUpperBound) {
209         // We know that the index definitely exceeds the upper bound.
210         reportOOB(checkerContext, state_exceedsUpperBound, OOB_Excedes);
211         return;
212       }
213       if (isTainted(state, ByteOffset)) {
214         // Both cases are possible, but the index is tainted, so report.
215         reportTaintOOB(checkerContext, state_exceedsUpperBound, ByteOffset);
216         return;
217       }
218     }
219 
220     if (state_withinUpperBound)
221       state = state_withinUpperBound;
222   }
223 
224   checkerContext.addTransition(state);
225 }
226 
227 void ArrayBoundCheckerV2::reportTaintOOB(CheckerContext &checkerContext,
228                                          ProgramStateRef errorState,
229                                          SVal TaintedSVal) const {
230   ExplodedNode *errorNode = checkerContext.generateErrorNode(errorState);
231   if (!errorNode)
232     return;
233 
234   if (!TaintBT)
235     TaintBT.reset(
236         new BugType(this, "Out-of-bound access", categories::TaintedData));
237 
238   SmallString<256> buf;
239   llvm::raw_svector_ostream os(buf);
240   os << "Out of bound memory access (index is tainted)";
241   auto BR =
242       std::make_unique<PathSensitiveBugReport>(*TaintBT, os.str(), errorNode);
243 
244   // Track back the propagation of taintedness.
245   for (SymbolRef Sym : getTaintedSymbols(errorState, TaintedSVal)) {
246     BR->markInteresting(Sym);
247   }
248 
249   checkerContext.emitReport(std::move(BR));
250 }
251 
252 void ArrayBoundCheckerV2::reportOOB(CheckerContext &checkerContext,
253                                     ProgramStateRef errorState,
254                                     OOB_Kind kind) const {
255 
256   ExplodedNode *errorNode = checkerContext.generateErrorNode(errorState);
257   if (!errorNode)
258     return;
259 
260   if (!BT)
261     BT.reset(new BuiltinBug(this, "Out-of-bound access"));
262 
263   // FIXME: This diagnostics are preliminary.  We should get far better
264   // diagnostics for explaining buffer overruns.
265 
266   SmallString<256> buf;
267   llvm::raw_svector_ostream os(buf);
268   os << "Out of bound memory access ";
269   switch (kind) {
270   case OOB_Precedes:
271     os << "(accessed memory precedes memory block)";
272     break;
273   case OOB_Excedes:
274     os << "(access exceeds upper limit of memory block)";
275     break;
276   }
277   auto BR = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), errorNode);
278   checkerContext.emitReport(std::move(BR));
279 }
280 
281 bool ArrayBoundCheckerV2::isFromCtypeMacro(const Stmt *S, ASTContext &ACtx) {
282   SourceLocation Loc = S->getBeginLoc();
283   if (!Loc.isMacroID())
284     return false;
285 
286   StringRef MacroName = Lexer::getImmediateMacroName(
287       Loc, ACtx.getSourceManager(), ACtx.getLangOpts());
288 
289   if (MacroName.size() < 7 || MacroName[0] != 'i' || MacroName[1] != 's')
290     return false;
291 
292   return ((MacroName == "isalnum") || (MacroName == "isalpha") ||
293           (MacroName == "isblank") || (MacroName == "isdigit") ||
294           (MacroName == "isgraph") || (MacroName == "islower") ||
295           (MacroName == "isnctrl") || (MacroName == "isprint") ||
296           (MacroName == "ispunct") || (MacroName == "isspace") ||
297           (MacroName == "isupper") || (MacroName == "isxdigit"));
298 }
299 
300 #ifndef NDEBUG
301 LLVM_DUMP_METHOD void RegionRawOffsetV2::dump() const {
302   dumpToStream(llvm::errs());
303 }
304 
305 void RegionRawOffsetV2::dumpToStream(raw_ostream &os) const {
306   os << "raw_offset_v2{" << getRegion() << ',' << getByteOffset() << '}';
307 }
308 #endif
309 
310 // Lazily computes a value to be used by 'computeOffset'.  If 'val'
311 // is unknown or undefined, we lazily substitute '0'.  Otherwise,
312 // return 'val'.
313 static inline SVal getValue(SVal val, SValBuilder &svalBuilder) {
314   return val.isUndef() ? svalBuilder.makeZeroArrayIndex() : val;
315 }
316 
317 // Scale a base value by a scaling factor, and return the scaled
318 // value as an SVal.  Used by 'computeOffset'.
319 static inline SVal scaleValue(ProgramStateRef state,
320                               NonLoc baseVal, CharUnits scaling,
321                               SValBuilder &sb) {
322   return sb.evalBinOpNN(state, BO_Mul, baseVal,
323                         sb.makeArrayIndex(scaling.getQuantity()),
324                         sb.getArrayIndexType());
325 }
326 
327 // Add an SVal to another, treating unknown and undefined values as
328 // summing to UnknownVal.  Used by 'computeOffset'.
329 static SVal addValue(ProgramStateRef state, SVal x, SVal y,
330                      SValBuilder &svalBuilder) {
331   // We treat UnknownVals and UndefinedVals the same here because we
332   // only care about computing offsets.
333   if (x.isUnknownOrUndef() || y.isUnknownOrUndef())
334     return UnknownVal();
335 
336   return svalBuilder.evalBinOpNN(state, BO_Add, x.castAs<NonLoc>(),
337                                  y.castAs<NonLoc>(),
338                                  svalBuilder.getArrayIndexType());
339 }
340 
341 /// Compute a raw byte offset from a base region.  Used for array bounds
342 /// checking.
343 RegionRawOffsetV2 RegionRawOffsetV2::computeOffset(ProgramStateRef state,
344                                                    SValBuilder &svalBuilder,
345                                                    SVal location)
346 {
347   const MemRegion *region = location.getAsRegion();
348   SVal offset = UndefinedVal();
349 
350   while (region) {
351     switch (region->getKind()) {
352       default: {
353         if (const SubRegion *subReg = dyn_cast<SubRegion>(region)) {
354           if (auto Offset = getValue(offset, svalBuilder).getAs<NonLoc>())
355             return RegionRawOffsetV2(subReg, *Offset);
356         }
357         return RegionRawOffsetV2();
358       }
359       case MemRegion::ElementRegionKind: {
360         const ElementRegion *elemReg = cast<ElementRegion>(region);
361         SVal index = elemReg->getIndex();
362         if (!isa<NonLoc>(index))
363           return RegionRawOffsetV2();
364         QualType elemType = elemReg->getElementType();
365         // If the element is an incomplete type, go no further.
366         ASTContext &astContext = svalBuilder.getContext();
367         if (elemType->isIncompleteType())
368           return RegionRawOffsetV2();
369 
370         // Update the offset.
371         offset = addValue(state,
372                           getValue(offset, svalBuilder),
373                           scaleValue(state,
374                           index.castAs<NonLoc>(),
375                           astContext.getTypeSizeInChars(elemType),
376                           svalBuilder),
377                           svalBuilder);
378 
379         if (offset.isUnknownOrUndef())
380           return RegionRawOffsetV2();
381 
382         region = elemReg->getSuperRegion();
383         continue;
384       }
385     }
386   }
387   return RegionRawOffsetV2();
388 }
389 
390 void ento::registerArrayBoundCheckerV2(CheckerManager &mgr) {
391   mgr.registerChecker<ArrayBoundCheckerV2>();
392 }
393 
394 bool ento::shouldRegisterArrayBoundCheckerV2(const CheckerManager &mgr) {
395   return true;
396 }
397