xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp (revision 5dc9e87c8cae7842edcaa4dd01308873109208da)
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_threshold is always false
305       return {nullptr, State};
306     }
307     // negative_value < unsigned_threshold is always true
308     return {State, nullptr};
309   }
310   if (isUnsigned(SVB, Value) && isNegative(SVB, State, Threshold)) {
311     // unsigned_value == negative_threshold and
312     // unsigned_value < negative_threshold are 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   // NOTE: We NEED to use the `evalBinOpNN` call in the "common" case, because
320   // we want to ensure that assumptions coming from this precondition and
321   // assumptions coming from regular C/C++ operator calls are represented by
322   // constraints on the same symbolic expression. A solution that would
323   // evaluate these "mathematical" compariosns through a separate pathway would
324   // be a step backwards in this sense.
325 
326   const BinaryOperatorKind OpKind = CheckEquality ? BO_EQ : BO_LT;
327   auto BelowThreshold =
328       SVB.evalBinOpNN(State, OpKind, Value, Threshold, SVB.getConditionType())
329           .getAs<NonLoc>();
330 
331   if (BelowThreshold)
332     return State->assume(*BelowThreshold);
333 
334   return {nullptr, nullptr};
335 }
336 
337 static std::string getRegionName(const SubRegion *Region) {
338   if (std::string RegName = Region->getDescriptiveName(); !RegName.empty())
339     return RegName;
340 
341   // Field regions only have descriptive names when their parent has a
342   // descriptive name; so we provide a fallback representation for them:
343   if (const auto *FR = Region->getAs<FieldRegion>()) {
344     if (StringRef Name = FR->getDecl()->getName(); !Name.empty())
345       return formatv("the field '{0}'", Name);
346     return "the unnamed field";
347   }
348 
349   if (isa<AllocaRegion>(Region))
350     return "the memory returned by 'alloca'";
351 
352   if (isa<SymbolicRegion>(Region) &&
353       isa<HeapSpaceRegion>(Region->getMemorySpace()))
354     return "the heap area";
355 
356   if (isa<StringRegion>(Region))
357     return "the string literal";
358 
359   return "the region";
360 }
361 
362 static std::optional<int64_t> getConcreteValue(NonLoc SV) {
363   if (auto ConcreteVal = SV.getAs<nonloc::ConcreteInt>()) {
364     return ConcreteVal->getValue().tryExtValue();
365   }
366   return std::nullopt;
367 }
368 
369 static std::optional<int64_t> getConcreteValue(std::optional<NonLoc> SV) {
370   return SV ? getConcreteValue(*SV) : std::nullopt;
371 }
372 
373 static Messages getPrecedesMsgs(const SubRegion *Region, NonLoc Offset) {
374   std::string RegName = getRegionName(Region);
375   SmallString<128> Buf;
376   llvm::raw_svector_ostream Out(Buf);
377   Out << "Access of " << RegName << " at negative byte offset";
378   if (auto ConcreteIdx = Offset.getAs<nonloc::ConcreteInt>())
379     Out << ' ' << ConcreteIdx->getValue();
380   return {formatv("Out of bound access to memory preceding {0}", RegName),
381           std::string(Buf)};
382 }
383 
384 /// Try to divide `Val1` and `Val2` (in place) by `Divisor` and return true if
385 /// it can be performed (`Divisor` is nonzero and there is no remainder). The
386 /// values `Val1` and `Val2` may be nullopt and in that case the corresponding
387 /// division is considered to be successful.
388 static bool tryDividePair(std::optional<int64_t> &Val1,
389                           std::optional<int64_t> &Val2, int64_t Divisor) {
390   if (!Divisor)
391     return false;
392   const bool Val1HasRemainder = Val1 && *Val1 % Divisor;
393   const bool Val2HasRemainder = Val2 && *Val2 % Divisor;
394   if (!Val1HasRemainder && !Val2HasRemainder) {
395     if (Val1)
396       *Val1 /= Divisor;
397     if (Val2)
398       *Val2 /= Divisor;
399     return true;
400   }
401   return false;
402 }
403 
404 static Messages getExceedsMsgs(ASTContext &ACtx, const SubRegion *Region,
405                                NonLoc Offset, NonLoc Extent, SVal Location) {
406   std::string RegName = getRegionName(Region);
407   const auto *EReg = Location.getAsRegion()->getAs<ElementRegion>();
408   assert(EReg && "this checker only handles element access");
409   QualType ElemType = EReg->getElementType();
410 
411   std::optional<int64_t> OffsetN = getConcreteValue(Offset);
412   std::optional<int64_t> ExtentN = getConcreteValue(Extent);
413 
414   int64_t ElemSize = ACtx.getTypeSizeInChars(ElemType).getQuantity();
415 
416   bool UseByteOffsets = !tryDividePair(OffsetN, ExtentN, ElemSize);
417 
418   SmallString<256> Buf;
419   llvm::raw_svector_ostream Out(Buf);
420   Out << "Access of ";
421   if (!ExtentN && !UseByteOffsets)
422     Out << "'" << ElemType.getAsString() << "' element in ";
423   Out << RegName << " at ";
424   if (OffsetN) {
425     Out << (UseByteOffsets ? "byte offset " : "index ") << *OffsetN;
426   } else {
427     Out << "an overflowing " << (UseByteOffsets ? "byte offset" : "index");
428   }
429   if (ExtentN) {
430     Out << ", while it holds only ";
431     if (*ExtentN != 1)
432       Out << *ExtentN;
433     else
434       Out << "a single";
435     if (UseByteOffsets)
436       Out << " byte";
437     else
438       Out << " '" << ElemType.getAsString() << "' element";
439 
440     if (*ExtentN > 1)
441       Out << "s";
442   }
443 
444   return {
445       formatv("Out of bound access to memory after the end of {0}", RegName),
446       std::string(Buf)};
447 }
448 
449 static Messages getTaintMsgs(const SubRegion *Region, const char *OffsetName) {
450   std::string RegName = getRegionName(Region);
451   return {formatv("Potential out of bound access to {0} with tainted {1}",
452                   RegName, OffsetName),
453           formatv("Access of {0} with a tainted {1} that may be too large",
454                   RegName, OffsetName)};
455 }
456 
457 const NoteTag *StateUpdateReporter::createNoteTag(CheckerContext &C) const {
458   // Don't create a note tag if we didn't assume anything:
459   if (!AssumedNonNegative && !AssumedUpperBound)
460     return nullptr;
461 
462   return C.getNoteTag([*this](PathSensitiveBugReport &BR) -> std::string {
463     return getMessage(BR);
464   });
465 }
466 
467 std::string StateUpdateReporter::getMessage(PathSensitiveBugReport &BR) const {
468   bool ShouldReportNonNegative = AssumedNonNegative;
469   if (!providesInformationAboutInteresting(ByteOffsetVal, BR)) {
470     if (AssumedUpperBound &&
471         providesInformationAboutInteresting(*AssumedUpperBound, BR)) {
472       // Even if the byte offset isn't interesting (e.g. it's a constant value),
473       // the assumption can still be interesting if it provides information
474       // about an interesting symbolic upper bound.
475       ShouldReportNonNegative = false;
476     } else {
477       // We don't have anything interesting, don't report the assumption.
478       return "";
479     }
480   }
481 
482   std::optional<int64_t> OffsetN = getConcreteValue(ByteOffsetVal);
483   std::optional<int64_t> ExtentN = getConcreteValue(AssumedUpperBound);
484 
485   const bool UseIndex =
486       ElementSize && tryDividePair(OffsetN, ExtentN, *ElementSize);
487 
488   SmallString<256> Buf;
489   llvm::raw_svector_ostream Out(Buf);
490   Out << "Assuming ";
491   if (UseIndex) {
492     Out << "index ";
493     if (OffsetN)
494       Out << "'" << OffsetN << "' ";
495   } else if (AssumedUpperBound) {
496     Out << "byte offset ";
497     if (OffsetN)
498       Out << "'" << OffsetN << "' ";
499   } else {
500     Out << "offset ";
501   }
502 
503   Out << "is";
504   if (ShouldReportNonNegative) {
505     Out << " non-negative";
506   }
507   if (AssumedUpperBound) {
508     if (ShouldReportNonNegative)
509       Out << " and";
510     Out << " less than ";
511     if (ExtentN)
512       Out << *ExtentN << ", ";
513     if (UseIndex && ElementType)
514       Out << "the number of '" << ElementType->getAsString()
515           << "' elements in ";
516     else
517       Out << "the extent of ";
518     Out << getRegionName(Reg);
519   }
520   return std::string(Out.str());
521 }
522 
523 bool StateUpdateReporter::providesInformationAboutInteresting(
524     SymbolRef Sym, PathSensitiveBugReport &BR) {
525   if (!Sym)
526     return false;
527   for (SymbolRef PartSym : Sym->symbols()) {
528     // The interestingess mark may appear on any layer as we're stripping off
529     // the SymIntExpr, UnarySymExpr etc. layers...
530     if (BR.isInteresting(PartSym))
531       return true;
532     // ...but if both sides of the expression are symbolic, then there is no
533     // practical algorithm to produce separate constraints for the two
534     // operands (from the single combined result).
535     if (isa<SymSymExpr>(PartSym))
536       return false;
537   }
538   return false;
539 }
540 
541 void ArrayBoundCheckerV2::performCheck(const Expr *E, CheckerContext &C) const {
542   const SVal Location = C.getSVal(E);
543 
544   // The header ctype.h (from e.g. glibc) implements the isXXXXX() macros as
545   //   #define isXXXXX(arg) (LOOKUP_TABLE[arg] & BITMASK_FOR_XXXXX)
546   // and incomplete analysis of these leads to false positives. As even
547   // accurate reports would be confusing for the users, just disable reports
548   // from these macros:
549   if (isFromCtypeMacro(E, C.getASTContext()))
550     return;
551 
552   ProgramStateRef State = C.getState();
553   SValBuilder &SVB = C.getSValBuilder();
554 
555   const std::optional<std::pair<const SubRegion *, NonLoc>> &RawOffset =
556       computeOffset(State, SVB, Location);
557 
558   if (!RawOffset)
559     return;
560 
561   auto [Reg, ByteOffset] = *RawOffset;
562 
563   // The state updates will be reported as a single note tag, which will be
564   // composed by this helper class.
565   StateUpdateReporter SUR(Reg, ByteOffset, E, C);
566 
567   // CHECK LOWER BOUND
568   const MemSpaceRegion *Space = Reg->getMemorySpace();
569   if (!(isa<SymbolicRegion>(Reg) && isa<UnknownSpaceRegion>(Space))) {
570     // A symbolic region in unknown space represents an unknown pointer that
571     // may point into the middle of an array, so we don't look for underflows.
572     // Both conditions are significant because we want to check underflows in
573     // symbolic regions on the heap (which may be introduced by checkers like
574     // MallocChecker that call SValBuilder::getConjuredHeapSymbolVal()) and
575     // non-symbolic regions (e.g. a field subregion of a symbolic region) in
576     // unknown space.
577     auto [PrecedesLowerBound, WithinLowerBound] = compareValueToThreshold(
578         State, ByteOffset, SVB.makeZeroArrayIndex(), SVB);
579 
580     if (PrecedesLowerBound) {
581       // The offset may be invalid (negative)...
582       if (!WithinLowerBound) {
583         // ...and it cannot be valid (>= 0), so report an error.
584         Messages Msgs = getPrecedesMsgs(Reg, ByteOffset);
585         reportOOB(C, PrecedesLowerBound, Msgs, ByteOffset, std::nullopt);
586         return;
587       }
588       // ...but it can be valid as well, so the checker will (optimistically)
589       // assume that it's valid and mention this in the note tag.
590       SUR.recordNonNegativeAssumption();
591     }
592 
593     // Actually update the state. The "if" only fails in the extremely unlikely
594     // case when compareValueToThreshold returns {nullptr, nullptr} becasue
595     // evalBinOpNN fails to evaluate the less-than operator.
596     if (WithinLowerBound)
597       State = WithinLowerBound;
598   }
599 
600   // CHECK UPPER BOUND
601   DefinedOrUnknownSVal Size = getDynamicExtent(State, Reg, SVB);
602   if (auto KnownSize = Size.getAs<NonLoc>()) {
603     auto [WithinUpperBound, ExceedsUpperBound] =
604         compareValueToThreshold(State, ByteOffset, *KnownSize, SVB);
605 
606     if (ExceedsUpperBound) {
607       // The offset may be invalid (>= Size)...
608       if (!WithinUpperBound) {
609         // ...and it cannot be within bounds, so report an error, unless we can
610         // definitely determine that this is an idiomatic `&array[size]`
611         // expression that calculates the past-the-end pointer.
612         if (isIdiomaticPastTheEndPtr(E, ExceedsUpperBound, ByteOffset,
613                                      *KnownSize, C)) {
614           C.addTransition(ExceedsUpperBound, SUR.createNoteTag(C));
615           return;
616         }
617 
618         Messages Msgs = getExceedsMsgs(C.getASTContext(), Reg, ByteOffset,
619                                        *KnownSize, Location);
620         reportOOB(C, ExceedsUpperBound, Msgs, ByteOffset, KnownSize);
621         return;
622       }
623       // ...and it can be valid as well...
624       if (isTainted(State, ByteOffset)) {
625         // ...but it's tainted, so report an error.
626 
627         // Diagnostic detail: saying "tainted offset" is always correct, but
628         // the common case is that 'idx' is tainted in 'arr[idx]' and then it's
629         // nicer to say "tainted index".
630         const char *OffsetName = "offset";
631         if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
632           if (isTainted(State, ASE->getIdx(), C.getLocationContext()))
633             OffsetName = "index";
634 
635         Messages Msgs = getTaintMsgs(Reg, OffsetName);
636         reportOOB(C, ExceedsUpperBound, Msgs, ByteOffset, KnownSize,
637                   /*IsTaintBug=*/true);
638         return;
639       }
640       // ...and it isn't tainted, so the checker will (optimistically) assume
641       // that the offset is in bounds and mention this in the note tag.
642       SUR.recordUpperBoundAssumption(*KnownSize);
643     }
644 
645     // Actually update the state. The "if" only fails in the extremely unlikely
646     // case when compareValueToThreshold returns {nullptr, nullptr} becasue
647     // evalBinOpNN fails to evaluate the less-than operator.
648     if (WithinUpperBound)
649       State = WithinUpperBound;
650   }
651 
652   // Add a transition, reporting the state updates that we accumulated.
653   C.addTransition(State, SUR.createNoteTag(C));
654 }
655 
656 void ArrayBoundCheckerV2::markPartsInteresting(PathSensitiveBugReport &BR,
657                                                ProgramStateRef ErrorState,
658                                                NonLoc Val, bool MarkTaint) {
659   if (SymbolRef Sym = Val.getAsSymbol()) {
660     // If the offset is a symbolic value, iterate over its "parts" with
661     // `SymExpr::symbols()` and mark each of them as interesting.
662     // For example, if the offset is `x*4 + y` then we put interestingness onto
663     // the SymSymExpr `x*4 + y`, the SymIntExpr `x*4` and the two data symbols
664     // `x` and `y`.
665     for (SymbolRef PartSym : Sym->symbols())
666       BR.markInteresting(PartSym);
667   }
668 
669   if (MarkTaint) {
670     // If the issue that we're reporting depends on the taintedness of the
671     // offset, then put interestingness onto symbols that could be the origin
672     // of the taint. Note that this may find symbols that did not appear in
673     // `Sym->symbols()` (because they're only loosely connected to `Val`).
674     for (SymbolRef Sym : getTaintedSymbols(ErrorState, Val))
675       BR.markInteresting(Sym);
676   }
677 }
678 
679 void ArrayBoundCheckerV2::reportOOB(CheckerContext &C,
680                                     ProgramStateRef ErrorState, Messages Msgs,
681                                     NonLoc Offset, std::optional<NonLoc> Extent,
682                                     bool IsTaintBug /*=false*/) const {
683 
684   ExplodedNode *ErrorNode = C.generateErrorNode(ErrorState);
685   if (!ErrorNode)
686     return;
687 
688   auto BR = std::make_unique<PathSensitiveBugReport>(
689       IsTaintBug ? TaintBT : BT, Msgs.Short, Msgs.Full, ErrorNode);
690 
691   // FIXME: ideally we would just call trackExpressionValue() and that would
692   // "do the right thing": mark the relevant symbols as interesting, track the
693   // control dependencies and statements storing the relevant values and add
694   // helpful diagnostic pieces. However, right now trackExpressionValue() is
695   // a heap of unreliable heuristics, so it would cause several issues:
696   // - Interestingness is not applied consistently, e.g. if `array[x+10]`
697   //   causes an overflow, then `x` is not marked as interesting.
698   // - We get irrelevant diagnostic pieces, e.g. in the code
699   //   `int *p = (int*)malloc(2*sizeof(int)); p[3] = 0;`
700   //   it places a "Storing uninitialized value" note on the `malloc` call
701   //   (which is technically true, but irrelevant).
702   // If trackExpressionValue() becomes reliable, it should be applied instead
703   // of this custom markPartsInteresting().
704   markPartsInteresting(*BR, ErrorState, Offset, IsTaintBug);
705   if (Extent)
706     markPartsInteresting(*BR, ErrorState, *Extent, IsTaintBug);
707 
708   C.emitReport(std::move(BR));
709 }
710 
711 bool ArrayBoundCheckerV2::isFromCtypeMacro(const Stmt *S, ASTContext &ACtx) {
712   SourceLocation Loc = S->getBeginLoc();
713   if (!Loc.isMacroID())
714     return false;
715 
716   StringRef MacroName = Lexer::getImmediateMacroName(
717       Loc, ACtx.getSourceManager(), ACtx.getLangOpts());
718 
719   if (MacroName.size() < 7 || MacroName[0] != 'i' || MacroName[1] != 's')
720     return false;
721 
722   return ((MacroName == "isalnum") || (MacroName == "isalpha") ||
723           (MacroName == "isblank") || (MacroName == "isdigit") ||
724           (MacroName == "isgraph") || (MacroName == "islower") ||
725           (MacroName == "isnctrl") || (MacroName == "isprint") ||
726           (MacroName == "ispunct") || (MacroName == "isspace") ||
727           (MacroName == "isupper") || (MacroName == "isxdigit"));
728 }
729 
730 bool ArrayBoundCheckerV2::isInAddressOf(const Stmt *S, ASTContext &ACtx) {
731   ParentMapContext &ParentCtx = ACtx.getParentMapContext();
732   do {
733     const DynTypedNodeList Parents = ParentCtx.getParents(*S);
734     if (Parents.empty())
735       return false;
736     S = Parents[0].get<Stmt>();
737   } while (isa_and_nonnull<ParenExpr, ImplicitCastExpr>(S));
738   const auto *UnaryOp = dyn_cast_or_null<UnaryOperator>(S);
739   return UnaryOp && UnaryOp->getOpcode() == UO_AddrOf;
740 }
741 
742 bool ArrayBoundCheckerV2::isIdiomaticPastTheEndPtr(const Expr *E,
743                                                    ProgramStateRef State,
744                                                    NonLoc Offset, NonLoc Limit,
745                                                    CheckerContext &C) {
746   if (isa<ArraySubscriptExpr>(E) && isInAddressOf(E, C.getASTContext())) {
747     auto [EqualsToThreshold, NotEqualToThreshold] = compareValueToThreshold(
748         State, Offset, Limit, C.getSValBuilder(), /*CheckEquality=*/true);
749     return EqualsToThreshold && !NotEqualToThreshold;
750   }
751   return false;
752 }
753 
754 void ento::registerArrayBoundCheckerV2(CheckerManager &mgr) {
755   mgr.registerChecker<ArrayBoundCheckerV2>();
756 }
757 
758 bool ento::shouldRegisterArrayBoundCheckerV2(const CheckerManager &mgr) {
759   return true;
760 }
761