xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp (revision fa8a21144ec9a6836e9bf1e3bf5cd0b2f058209e)
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/AST/ParentMapContext.h"
16 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
17 #include "clang/StaticAnalyzer/Checkers/Taint.h"
18 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
19 #include "clang/StaticAnalyzer/Core/Checker.h"
20 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/Support/FormatVariadic.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <optional>
29 
30 using namespace clang;
31 using namespace ento;
32 using namespace taint;
33 using llvm::formatv;
34 
35 namespace {
36 /// If `E` is a "clean" array subscript expression, return the type of the
37 /// accessed element. If the base of the subscript expression is modified by
38 /// pointer arithmetic (and not the beginning of a "full" memory region), this
39 /// always returns nullopt because that's the right (or the least bad) thing to
40 /// do for the diagnostic output that's relying on this.
41 static std::optional<QualType> determineElementType(const Expr *E,
42                                                     const CheckerContext &C) {
43   const auto *ASE = dyn_cast<ArraySubscriptExpr>(E);
44   if (!ASE)
45     return std::nullopt;
46 
47   const MemRegion *SubscriptBaseReg = C.getSVal(ASE->getBase()).getAsRegion();
48   if (!SubscriptBaseReg)
49     return std::nullopt;
50 
51   // The base of the subscript expression is affected by pointer arithmetics,
52   // so we want to report byte offsets instead of indices.
53   if (isa<ElementRegion>(SubscriptBaseReg->StripCasts()))
54     return std::nullopt;
55 
56   return ASE->getType();
57 }
58 
59 static std::optional<int64_t>
60 determineElementSize(const std::optional<QualType> T, const CheckerContext &C) {
61   if (!T)
62     return std::nullopt;
63   return C.getASTContext().getTypeSizeInChars(*T).getQuantity();
64 }
65 
66 class StateUpdateReporter {
67   const SubRegion *Reg;
68   const NonLoc ByteOffsetVal;
69   const std::optional<QualType> ElementType;
70   const std::optional<int64_t> ElementSize;
71   bool AssumedNonNegative = false;
72   std::optional<NonLoc> AssumedUpperBound = std::nullopt;
73 
74 public:
75   StateUpdateReporter(const SubRegion *R, NonLoc ByteOffsVal, const Expr *E,
76                       CheckerContext &C)
77       : Reg(R), ByteOffsetVal(ByteOffsVal),
78         ElementType(determineElementType(E, C)),
79         ElementSize(determineElementSize(ElementType, C)) {}
80 
81   void recordNonNegativeAssumption() { AssumedNonNegative = true; }
82   void recordUpperBoundAssumption(NonLoc UpperBoundVal) {
83     AssumedUpperBound = UpperBoundVal;
84   }
85 
86   const NoteTag *createNoteTag(CheckerContext &C) const;
87 
88 private:
89   std::string getMessage(PathSensitiveBugReport &BR) const;
90 
91   /// Return true if information about the value of `Sym` can put constraints
92   /// on some symbol which is interesting within the bug report `BR`.
93   /// In particular, this returns true when `Sym` is interesting within `BR`;
94   /// but it also returns true if `Sym` is an expression that contains integer
95   /// constants and a single symbolic operand which is interesting (in `BR`).
96   /// We need to use this instead of plain `BR.isInteresting()` because if we
97   /// are analyzing code like
98   ///   int array[10];
99   ///   int f(int arg) {
100   ///     return array[arg] && array[arg + 10];
101   ///   }
102   /// then the byte offsets are `arg * 4` and `(arg + 10) * 4`, which are not
103   /// sub-expressions of each other (but `getSimplifiedOffsets` is smart enough
104   /// to detect this out of bounds access).
105   static bool providesInformationAboutInteresting(SymbolRef Sym,
106                                                   PathSensitiveBugReport &BR);
107   static bool providesInformationAboutInteresting(SVal SV,
108                                                   PathSensitiveBugReport &BR) {
109     return providesInformationAboutInteresting(SV.getAsSymbol(), BR);
110   }
111 };
112 
113 struct Messages {
114   std::string Short, Full;
115 };
116 
117 // NOTE: The `ArraySubscriptExpr` and `UnaryOperator` callbacks are `PostStmt`
118 // instead of `PreStmt` because the current implementation passes the whole
119 // expression to `CheckerContext::getSVal()` which only works after the
120 // symbolic evaluation of the expression. (To turn them into `PreStmt`
121 // callbacks, we'd need to duplicate the logic that evaluates these
122 // expressions.) The `MemberExpr` callback would work as `PreStmt` but it's
123 // defined as `PostStmt` for the sake of consistency with the other callbacks.
124 class ArrayBoundCheckerV2 : public Checker<check::PostStmt<ArraySubscriptExpr>,
125                                            check::PostStmt<UnaryOperator>,
126                                            check::PostStmt<MemberExpr>> {
127   BugType BT{this, "Out-of-bound access"};
128   BugType TaintBT{this, "Out-of-bound access", categories::TaintedData};
129 
130   void performCheck(const Expr *E, CheckerContext &C) const;
131 
132   void reportOOB(CheckerContext &C, ProgramStateRef ErrorState, Messages Msgs,
133                  NonLoc Offset, std::optional<NonLoc> Extent,
134                  bool IsTaintBug = false) const;
135 
136   static void markPartsInteresting(PathSensitiveBugReport &BR,
137                                    ProgramStateRef ErrorState, NonLoc Val,
138                                    bool MarkTaint);
139 
140   static bool isFromCtypeMacro(const Stmt *S, ASTContext &AC);
141 
142   static bool isIdiomaticPastTheEndPtr(const Expr *E, ProgramStateRef State,
143                                        NonLoc Offset, NonLoc Limit,
144                                        CheckerContext &C);
145   static bool isInAddressOf(const Stmt *S, ASTContext &AC);
146 
147 public:
148   void checkPostStmt(const ArraySubscriptExpr *E, CheckerContext &C) const {
149     performCheck(E, C);
150   }
151   void checkPostStmt(const UnaryOperator *E, CheckerContext &C) const {
152     if (E->getOpcode() == UO_Deref)
153       performCheck(E, C);
154   }
155   void checkPostStmt(const MemberExpr *E, CheckerContext &C) const {
156     if (E->isArrow())
157       performCheck(E->getBase(), C);
158   }
159 };
160 
161 } // anonymous namespace
162 
163 /// For a given Location that can be represented as a symbolic expression
164 /// Arr[Idx] (or perhaps Arr[Idx1][Idx2] etc.), return the parent memory block
165 /// Arr and the distance of Location from the beginning of Arr (expressed in a
166 /// NonLoc that specifies the number of CharUnits). Returns nullopt when these
167 /// cannot be determined.
168 static std::optional<std::pair<const SubRegion *, NonLoc>>
169 computeOffset(ProgramStateRef State, SValBuilder &SVB, SVal Location) {
170   QualType T = SVB.getArrayIndexType();
171   auto EvalBinOp = [&SVB, State, T](BinaryOperatorKind Op, NonLoc L, NonLoc R) {
172     // We will use this utility to add and multiply values.
173     return SVB.evalBinOpNN(State, Op, L, R, T).getAs<NonLoc>();
174   };
175 
176   const SubRegion *OwnerRegion = nullptr;
177   std::optional<NonLoc> Offset = SVB.makeZeroArrayIndex();
178 
179   const ElementRegion *CurRegion =
180       dyn_cast_or_null<ElementRegion>(Location.getAsRegion());
181 
182   while (CurRegion) {
183     const auto Index = CurRegion->getIndex().getAs<NonLoc>();
184     if (!Index)
185       return std::nullopt;
186 
187     QualType ElemType = CurRegion->getElementType();
188 
189     // FIXME: The following early return was presumably added to safeguard the
190     // getTypeSizeInChars() call (which doesn't accept an incomplete type), but
191     // it seems that `ElemType` cannot be incomplete at this point.
192     if (ElemType->isIncompleteType())
193       return std::nullopt;
194 
195     // Calculate Delta = Index * sizeof(ElemType).
196     NonLoc Size = SVB.makeArrayIndex(
197         SVB.getContext().getTypeSizeInChars(ElemType).getQuantity());
198     auto Delta = EvalBinOp(BO_Mul, *Index, Size);
199     if (!Delta)
200       return std::nullopt;
201 
202     // Perform Offset += Delta.
203     Offset = EvalBinOp(BO_Add, *Offset, *Delta);
204     if (!Offset)
205       return std::nullopt;
206 
207     OwnerRegion = CurRegion->getSuperRegion()->getAs<SubRegion>();
208     // When this is just another ElementRegion layer, we need to continue the
209     // offset calculations:
210     CurRegion = dyn_cast_or_null<ElementRegion>(OwnerRegion);
211   }
212 
213   if (OwnerRegion)
214     return std::make_pair(OwnerRegion, *Offset);
215 
216   return std::nullopt;
217 }
218 
219 // NOTE: This function is the "heart" of this checker. It simplifies
220 // inequalities with transformations that are valid (and very elementary) in
221 // pure mathematics, but become invalid if we use them in C++ number model
222 // where the calculations may overflow.
223 // Due to the overflow issues I think it's impossible (or at least not
224 // practical) to integrate this kind of simplification into the resolution of
225 // arbitrary inequalities (i.e. the code of `evalBinOp`); but this function
226 // produces valid results when the calculations are handling memory offsets
227 // and every value is well below SIZE_MAX.
228 // TODO: This algorithm should be moved to a central location where it's
229 // available for other checkers that need to compare memory offsets.
230 // NOTE: the simplification preserves the order of the two operands in a
231 // mathematical sense, but it may change the result produced by a C++
232 // comparison operator (and the automatic type conversions).
233 // For example, consider a comparison "X+1 < 0", where the LHS is stored as a
234 // size_t and the RHS is stored in an int. (As size_t is unsigned, this
235 // comparison is false for all values of "X".) However, the simplification may
236 // turn it into "X < -1", which is still always false in a mathematical sense,
237 // but can produce a true result when evaluated by `evalBinOp` (which follows
238 // the rules of C++ and casts -1 to SIZE_MAX).
239 static std::pair<NonLoc, nonloc::ConcreteInt>
240 getSimplifiedOffsets(NonLoc offset, nonloc::ConcreteInt extent,
241                      SValBuilder &svalBuilder) {
242   std::optional<nonloc::SymbolVal> SymVal = offset.getAs<nonloc::SymbolVal>();
243   if (SymVal && SymVal->isExpression()) {
244     if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SymVal->getSymbol())) {
245       llvm::APSInt constant =
246           APSIntType(extent.getValue()).convert(SIE->getRHS());
247       switch (SIE->getOpcode()) {
248       case BO_Mul:
249         // The constant should never be 0 here, becasue multiplication by zero
250         // is simplified by the engine.
251         if ((extent.getValue() % constant) != 0)
252           return std::pair<NonLoc, nonloc::ConcreteInt>(offset, extent);
253         else
254           return getSimplifiedOffsets(
255               nonloc::SymbolVal(SIE->getLHS()),
256               svalBuilder.makeIntVal(extent.getValue() / constant),
257               svalBuilder);
258       case BO_Add:
259         return getSimplifiedOffsets(
260             nonloc::SymbolVal(SIE->getLHS()),
261             svalBuilder.makeIntVal(extent.getValue() - constant), svalBuilder);
262       default:
263         break;
264       }
265     }
266   }
267 
268   return std::pair<NonLoc, nonloc::ConcreteInt>(offset, extent);
269 }
270 
271 static bool isNegative(SValBuilder &SVB, ProgramStateRef State, NonLoc Value) {
272   const llvm::APSInt *MaxV = SVB.getMaxValue(State, Value);
273   return MaxV && MaxV->isNegative();
274 }
275 
276 static bool isUnsigned(SValBuilder &SVB, NonLoc Value) {
277   QualType T = Value.getType(SVB.getContext());
278   return T->isUnsignedIntegerType();
279 }
280 
281 // Evaluate the comparison Value < Threshold with the help of the custom
282 // simplification algorithm defined for this checker. Return a pair of states,
283 // where the first one corresponds to "value below threshold" and the second
284 // corresponds to "value at or above threshold". Returns {nullptr, nullptr} in
285 // the case when the evaluation fails.
286 // If the optional argument CheckEquality is true, then use BO_EQ instead of
287 // the default BO_LT after consistently applying the same simplification steps.
288 static std::pair<ProgramStateRef, ProgramStateRef>
289 compareValueToThreshold(ProgramStateRef State, NonLoc Value, NonLoc Threshold,
290                         SValBuilder &SVB, bool CheckEquality = false) {
291   if (auto ConcreteThreshold = Threshold.getAs<nonloc::ConcreteInt>()) {
292     std::tie(Value, Threshold) = getSimplifiedOffsets(Value, *ConcreteThreshold, SVB);
293   }
294 
295   // We want to perform a _mathematical_ comparison between the numbers `Value`
296   // and `Threshold`; but `evalBinOpNN` evaluates a C/C++ operator that may
297   // perform automatic conversions. For example the number -1 is less than the
298   // number 1000, but -1 < `1000ull` will evaluate to `false` because the `int`
299   // -1 is converted to ULONGLONG_MAX.
300   // To avoid automatic conversions, we evaluate the "obvious" cases without
301   // calling `evalBinOpNN`:
302   if (isNegative(SVB, State, Value) && isUnsigned(SVB, Threshold)) {
303     if (CheckEquality) {
304       // negative_value == unsigned_value is always false
305       return {nullptr, State};
306     }
307     // negative_value < unsigned_value is always false
308     return {State, nullptr};
309   }
310   if (isUnsigned(SVB, Value) && isNegative(SVB, State, Threshold)) {
311     // unsigned_value == negative_value and unsigned_value < negative_value are
312     // both always false
313     return {nullptr, State};
314   }
315   // FIXME: these special cases are sufficient for handling real-world
316   // comparisons, but in theory there could be contrived situations where
317   // automatic conversion of a symbolic value (which can be negative and can be
318   // positive) leads to incorrect results.
319 
320   const BinaryOperatorKind OpKind = CheckEquality ? BO_EQ : BO_LT;
321   auto BelowThreshold =
322       SVB.evalBinOpNN(State, OpKind, Value, Threshold, SVB.getConditionType())
323           .getAs<NonLoc>();
324 
325   if (BelowThreshold)
326     return State->assume(*BelowThreshold);
327 
328   return {nullptr, nullptr};
329 }
330 
331 static std::string getRegionName(const SubRegion *Region) {
332   if (std::string RegName = Region->getDescriptiveName(); !RegName.empty())
333     return RegName;
334 
335   // Field regions only have descriptive names when their parent has a
336   // descriptive name; so we provide a fallback representation for them:
337   if (const auto *FR = Region->getAs<FieldRegion>()) {
338     if (StringRef Name = FR->getDecl()->getName(); !Name.empty())
339       return formatv("the field '{0}'", Name);
340     return "the unnamed field";
341   }
342 
343   if (isa<AllocaRegion>(Region))
344     return "the memory returned by 'alloca'";
345 
346   if (isa<SymbolicRegion>(Region) &&
347       isa<HeapSpaceRegion>(Region->getMemorySpace()))
348     return "the heap area";
349 
350   if (isa<StringRegion>(Region))
351     return "the string literal";
352 
353   return "the region";
354 }
355 
356 static std::optional<int64_t> getConcreteValue(NonLoc SV) {
357   if (auto ConcreteVal = SV.getAs<nonloc::ConcreteInt>()) {
358     return ConcreteVal->getValue().tryExtValue();
359   }
360   return std::nullopt;
361 }
362 
363 static std::optional<int64_t> getConcreteValue(std::optional<NonLoc> SV) {
364   return SV ? getConcreteValue(*SV) : std::nullopt;
365 }
366 
367 static Messages getPrecedesMsgs(const SubRegion *Region, NonLoc Offset) {
368   std::string RegName = getRegionName(Region);
369   SmallString<128> Buf;
370   llvm::raw_svector_ostream Out(Buf);
371   Out << "Access of " << RegName << " at negative byte offset";
372   if (auto ConcreteIdx = Offset.getAs<nonloc::ConcreteInt>())
373     Out << ' ' << ConcreteIdx->getValue();
374   return {formatv("Out of bound access to memory preceding {0}", RegName),
375           std::string(Buf)};
376 }
377 
378 /// Try to divide `Val1` and `Val2` (in place) by `Divisor` and return true if
379 /// it can be performed (`Divisor` is nonzero and there is no remainder). The
380 /// values `Val1` and `Val2` may be nullopt and in that case the corresponding
381 /// division is considered to be successful.
382 static bool tryDividePair(std::optional<int64_t> &Val1,
383                           std::optional<int64_t> &Val2, int64_t Divisor) {
384   if (!Divisor)
385     return false;
386   const bool Val1HasRemainder = Val1 && *Val1 % Divisor;
387   const bool Val2HasRemainder = Val2 && *Val2 % Divisor;
388   if (!Val1HasRemainder && !Val2HasRemainder) {
389     if (Val1)
390       *Val1 /= Divisor;
391     if (Val2)
392       *Val2 /= Divisor;
393     return true;
394   }
395   return false;
396 }
397 
398 static Messages getExceedsMsgs(ASTContext &ACtx, const SubRegion *Region,
399                                NonLoc Offset, NonLoc Extent, SVal Location) {
400   std::string RegName = getRegionName(Region);
401   const auto *EReg = Location.getAsRegion()->getAs<ElementRegion>();
402   assert(EReg && "this checker only handles element access");
403   QualType ElemType = EReg->getElementType();
404 
405   std::optional<int64_t> OffsetN = getConcreteValue(Offset);
406   std::optional<int64_t> ExtentN = getConcreteValue(Extent);
407 
408   int64_t ElemSize = ACtx.getTypeSizeInChars(ElemType).getQuantity();
409 
410   bool UseByteOffsets = !tryDividePair(OffsetN, ExtentN, ElemSize);
411 
412   SmallString<256> Buf;
413   llvm::raw_svector_ostream Out(Buf);
414   Out << "Access of ";
415   if (!ExtentN && !UseByteOffsets)
416     Out << "'" << ElemType.getAsString() << "' element in ";
417   Out << RegName << " at ";
418   if (OffsetN) {
419     Out << (UseByteOffsets ? "byte offset " : "index ") << *OffsetN;
420   } else {
421     Out << "an overflowing " << (UseByteOffsets ? "byte offset" : "index");
422   }
423   if (ExtentN) {
424     Out << ", while it holds only ";
425     if (*ExtentN != 1)
426       Out << *ExtentN;
427     else
428       Out << "a single";
429     if (UseByteOffsets)
430       Out << " byte";
431     else
432       Out << " '" << ElemType.getAsString() << "' element";
433 
434     if (*ExtentN > 1)
435       Out << "s";
436   }
437 
438   return {
439       formatv("Out of bound access to memory after the end of {0}", RegName),
440       std::string(Buf)};
441 }
442 
443 static Messages getTaintMsgs(const SubRegion *Region, const char *OffsetName) {
444   std::string RegName = getRegionName(Region);
445   return {formatv("Potential out of bound access to {0} with tainted {1}",
446                   RegName, OffsetName),
447           formatv("Access of {0} with a tainted {1} that may be too large",
448                   RegName, OffsetName)};
449 }
450 
451 const NoteTag *StateUpdateReporter::createNoteTag(CheckerContext &C) const {
452   // Don't create a note tag if we didn't assume anything:
453   if (!AssumedNonNegative && !AssumedUpperBound)
454     return nullptr;
455 
456   return C.getNoteTag([*this](PathSensitiveBugReport &BR) -> std::string {
457     return getMessage(BR);
458   });
459 }
460 
461 std::string StateUpdateReporter::getMessage(PathSensitiveBugReport &BR) const {
462   bool ShouldReportNonNegative = AssumedNonNegative;
463   if (!providesInformationAboutInteresting(ByteOffsetVal, BR)) {
464     if (AssumedUpperBound &&
465         providesInformationAboutInteresting(*AssumedUpperBound, BR)) {
466       // Even if the byte offset isn't interesting (e.g. it's a constant value),
467       // the assumption can still be interesting if it provides information
468       // about an interesting symbolic upper bound.
469       ShouldReportNonNegative = false;
470     } else {
471       // We don't have anything interesting, don't report the assumption.
472       return "";
473     }
474   }
475 
476   std::optional<int64_t> OffsetN = getConcreteValue(ByteOffsetVal);
477   std::optional<int64_t> ExtentN = getConcreteValue(AssumedUpperBound);
478 
479   const bool UseIndex =
480       ElementSize && tryDividePair(OffsetN, ExtentN, *ElementSize);
481 
482   SmallString<256> Buf;
483   llvm::raw_svector_ostream Out(Buf);
484   Out << "Assuming ";
485   if (UseIndex) {
486     Out << "index ";
487     if (OffsetN)
488       Out << "'" << OffsetN << "' ";
489   } else if (AssumedUpperBound) {
490     Out << "byte offset ";
491     if (OffsetN)
492       Out << "'" << OffsetN << "' ";
493   } else {
494     Out << "offset ";
495   }
496 
497   Out << "is";
498   if (ShouldReportNonNegative) {
499     Out << " non-negative";
500   }
501   if (AssumedUpperBound) {
502     if (ShouldReportNonNegative)
503       Out << " and";
504     Out << " less than ";
505     if (ExtentN)
506       Out << *ExtentN << ", ";
507     if (UseIndex && ElementType)
508       Out << "the number of '" << ElementType->getAsString()
509           << "' elements in ";
510     else
511       Out << "the extent of ";
512     Out << getRegionName(Reg);
513   }
514   return std::string(Out.str());
515 }
516 
517 bool StateUpdateReporter::providesInformationAboutInteresting(
518     SymbolRef Sym, PathSensitiveBugReport &BR) {
519   if (!Sym)
520     return false;
521   for (SymbolRef PartSym : Sym->symbols()) {
522     // The interestingess mark may appear on any layer as we're stripping off
523     // the SymIntExpr, UnarySymExpr etc. layers...
524     if (BR.isInteresting(PartSym))
525       return true;
526     // ...but if both sides of the expression are symbolic, then there is no
527     // practical algorithm to produce separate constraints for the two
528     // operands (from the single combined result).
529     if (isa<SymSymExpr>(PartSym))
530       return false;
531   }
532   return false;
533 }
534 
535 void ArrayBoundCheckerV2::performCheck(const Expr *E, CheckerContext &C) const {
536   const SVal Location = C.getSVal(E);
537 
538   // The header ctype.h (from e.g. glibc) implements the isXXXXX() macros as
539   //   #define isXXXXX(arg) (LOOKUP_TABLE[arg] & BITMASK_FOR_XXXXX)
540   // and incomplete analysis of these leads to false positives. As even
541   // accurate reports would be confusing for the users, just disable reports
542   // from these macros:
543   if (isFromCtypeMacro(E, C.getASTContext()))
544     return;
545 
546   ProgramStateRef State = C.getState();
547   SValBuilder &SVB = C.getSValBuilder();
548 
549   const std::optional<std::pair<const SubRegion *, NonLoc>> &RawOffset =
550       computeOffset(State, SVB, Location);
551 
552   if (!RawOffset)
553     return;
554 
555   auto [Reg, ByteOffset] = *RawOffset;
556 
557   // The state updates will be reported as a single note tag, which will be
558   // composed by this helper class.
559   StateUpdateReporter SUR(Reg, ByteOffset, E, C);
560 
561   // CHECK LOWER BOUND
562   const MemSpaceRegion *Space = Reg->getMemorySpace();
563   if (!(isa<SymbolicRegion>(Reg) && isa<UnknownSpaceRegion>(Space))) {
564     // A symbolic region in unknown space represents an unknown pointer that
565     // may point into the middle of an array, so we don't look for underflows.
566     // Both conditions are significant because we want to check underflows in
567     // symbolic regions on the heap (which may be introduced by checkers like
568     // MallocChecker that call SValBuilder::getConjuredHeapSymbolVal()) and
569     // non-symbolic regions (e.g. a field subregion of a symbolic region) in
570     // unknown space.
571     auto [PrecedesLowerBound, WithinLowerBound] = compareValueToThreshold(
572         State, ByteOffset, SVB.makeZeroArrayIndex(), SVB);
573 
574     if (PrecedesLowerBound) {
575       // The offset may be invalid (negative)...
576       if (!WithinLowerBound) {
577         // ...and it cannot be valid (>= 0), so report an error.
578         Messages Msgs = getPrecedesMsgs(Reg, ByteOffset);
579         reportOOB(C, PrecedesLowerBound, Msgs, ByteOffset, std::nullopt);
580         return;
581       }
582       // ...but it can be valid as well, so the checker will (optimistically)
583       // assume that it's valid and mention this in the note tag.
584       SUR.recordNonNegativeAssumption();
585     }
586 
587     // Actually update the state. The "if" only fails in the extremely unlikely
588     // case when compareValueToThreshold returns {nullptr, nullptr} becasue
589     // evalBinOpNN fails to evaluate the less-than operator.
590     if (WithinLowerBound)
591       State = WithinLowerBound;
592   }
593 
594   // CHECK UPPER BOUND
595   DefinedOrUnknownSVal Size = getDynamicExtent(State, Reg, SVB);
596   if (auto KnownSize = Size.getAs<NonLoc>()) {
597     auto [WithinUpperBound, ExceedsUpperBound] =
598         compareValueToThreshold(State, ByteOffset, *KnownSize, SVB);
599 
600     if (ExceedsUpperBound) {
601       // The offset may be invalid (>= Size)...
602       if (!WithinUpperBound) {
603         // ...and it cannot be within bounds, so report an error, unless we can
604         // definitely determine that this is an idiomatic `&array[size]`
605         // expression that calculates the past-the-end pointer.
606         if (isIdiomaticPastTheEndPtr(E, ExceedsUpperBound, ByteOffset,
607                                      *KnownSize, C)) {
608           C.addTransition(ExceedsUpperBound, SUR.createNoteTag(C));
609           return;
610         }
611 
612         Messages Msgs = getExceedsMsgs(C.getASTContext(), Reg, ByteOffset,
613                                        *KnownSize, Location);
614         reportOOB(C, ExceedsUpperBound, Msgs, ByteOffset, KnownSize);
615         return;
616       }
617       // ...and it can be valid as well...
618       if (isTainted(State, ByteOffset)) {
619         // ...but it's tainted, so report an error.
620 
621         // Diagnostic detail: saying "tainted offset" is always correct, but
622         // the common case is that 'idx' is tainted in 'arr[idx]' and then it's
623         // nicer to say "tainted index".
624         const char *OffsetName = "offset";
625         if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
626           if (isTainted(State, ASE->getIdx(), C.getLocationContext()))
627             OffsetName = "index";
628 
629         Messages Msgs = getTaintMsgs(Reg, OffsetName);
630         reportOOB(C, ExceedsUpperBound, Msgs, ByteOffset, KnownSize,
631                   /*IsTaintBug=*/true);
632         return;
633       }
634       // ...and it isn't tainted, so the checker will (optimistically) assume
635       // that the offset is in bounds and mention this in the note tag.
636       SUR.recordUpperBoundAssumption(*KnownSize);
637     }
638 
639     // Actually update the state. The "if" only fails in the extremely unlikely
640     // case when compareValueToThreshold returns {nullptr, nullptr} becasue
641     // evalBinOpNN fails to evaluate the less-than operator.
642     if (WithinUpperBound)
643       State = WithinUpperBound;
644   }
645 
646   // Add a transition, reporting the state updates that we accumulated.
647   C.addTransition(State, SUR.createNoteTag(C));
648 }
649 
650 void ArrayBoundCheckerV2::markPartsInteresting(PathSensitiveBugReport &BR,
651                                                ProgramStateRef ErrorState,
652                                                NonLoc Val, bool MarkTaint) {
653   if (SymbolRef Sym = Val.getAsSymbol()) {
654     // If the offset is a symbolic value, iterate over its "parts" with
655     // `SymExpr::symbols()` and mark each of them as interesting.
656     // For example, if the offset is `x*4 + y` then we put interestingness onto
657     // the SymSymExpr `x*4 + y`, the SymIntExpr `x*4` and the two data symbols
658     // `x` and `y`.
659     for (SymbolRef PartSym : Sym->symbols())
660       BR.markInteresting(PartSym);
661   }
662 
663   if (MarkTaint) {
664     // If the issue that we're reporting depends on the taintedness of the
665     // offset, then put interestingness onto symbols that could be the origin
666     // of the taint. Note that this may find symbols that did not appear in
667     // `Sym->symbols()` (because they're only loosely connected to `Val`).
668     for (SymbolRef Sym : getTaintedSymbols(ErrorState, Val))
669       BR.markInteresting(Sym);
670   }
671 }
672 
673 void ArrayBoundCheckerV2::reportOOB(CheckerContext &C,
674                                     ProgramStateRef ErrorState, Messages Msgs,
675                                     NonLoc Offset, std::optional<NonLoc> Extent,
676                                     bool IsTaintBug /*=false*/) const {
677 
678   ExplodedNode *ErrorNode = C.generateErrorNode(ErrorState);
679   if (!ErrorNode)
680     return;
681 
682   auto BR = std::make_unique<PathSensitiveBugReport>(
683       IsTaintBug ? TaintBT : BT, Msgs.Short, Msgs.Full, ErrorNode);
684 
685   // FIXME: ideally we would just call trackExpressionValue() and that would
686   // "do the right thing": mark the relevant symbols as interesting, track the
687   // control dependencies and statements storing the relevant values and add
688   // helpful diagnostic pieces. However, right now trackExpressionValue() is
689   // a heap of unreliable heuristics, so it would cause several issues:
690   // - Interestingness is not applied consistently, e.g. if `array[x+10]`
691   //   causes an overflow, then `x` is not marked as interesting.
692   // - We get irrelevant diagnostic pieces, e.g. in the code
693   //   `int *p = (int*)malloc(2*sizeof(int)); p[3] = 0;`
694   //   it places a "Storing uninitialized value" note on the `malloc` call
695   //   (which is technically true, but irrelevant).
696   // If trackExpressionValue() becomes reliable, it should be applied instead
697   // of this custom markPartsInteresting().
698   markPartsInteresting(*BR, ErrorState, Offset, IsTaintBug);
699   if (Extent)
700     markPartsInteresting(*BR, ErrorState, *Extent, IsTaintBug);
701 
702   C.emitReport(std::move(BR));
703 }
704 
705 bool ArrayBoundCheckerV2::isFromCtypeMacro(const Stmt *S, ASTContext &ACtx) {
706   SourceLocation Loc = S->getBeginLoc();
707   if (!Loc.isMacroID())
708     return false;
709 
710   StringRef MacroName = Lexer::getImmediateMacroName(
711       Loc, ACtx.getSourceManager(), ACtx.getLangOpts());
712 
713   if (MacroName.size() < 7 || MacroName[0] != 'i' || MacroName[1] != 's')
714     return false;
715 
716   return ((MacroName == "isalnum") || (MacroName == "isalpha") ||
717           (MacroName == "isblank") || (MacroName == "isdigit") ||
718           (MacroName == "isgraph") || (MacroName == "islower") ||
719           (MacroName == "isnctrl") || (MacroName == "isprint") ||
720           (MacroName == "ispunct") || (MacroName == "isspace") ||
721           (MacroName == "isupper") || (MacroName == "isxdigit"));
722 }
723 
724 bool ArrayBoundCheckerV2::isInAddressOf(const Stmt *S, ASTContext &ACtx) {
725   ParentMapContext &ParentCtx = ACtx.getParentMapContext();
726   do {
727     const DynTypedNodeList Parents = ParentCtx.getParents(*S);
728     if (Parents.empty())
729       return false;
730     S = Parents[0].get<Stmt>();
731   } while (isa_and_nonnull<ParenExpr, ImplicitCastExpr>(S));
732   const auto *UnaryOp = dyn_cast_or_null<UnaryOperator>(S);
733   return UnaryOp && UnaryOp->getOpcode() == UO_AddrOf;
734 }
735 
736 bool ArrayBoundCheckerV2::isIdiomaticPastTheEndPtr(const Expr *E,
737                                                    ProgramStateRef State,
738                                                    NonLoc Offset, NonLoc Limit,
739                                                    CheckerContext &C) {
740   if (isa<ArraySubscriptExpr>(E) && isInAddressOf(E, C.getASTContext())) {
741     auto [EqualsToThreshold, NotEqualToThreshold] = compareValueToThreshold(
742         State, Offset, Limit, C.getSValBuilder(), /*CheckEquality=*/true);
743     return EqualsToThreshold && !NotEqualToThreshold;
744   }
745   return false;
746 }
747 
748 void ento::registerArrayBoundCheckerV2(CheckerManager &mgr) {
749   mgr.registerChecker<ArrayBoundCheckerV2>();
750 }
751 
752 bool ento::shouldRegisterArrayBoundCheckerV2(const CheckerManager &mgr) {
753   return true;
754 }
755