xref: /freebsd/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp (revision 770cf0a5f02dc8983a89c6568d741fbc25baa999)
1 //= CStringChecker.cpp - Checks calls to C string functions --------*- 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 defines CStringChecker, which is an assortment of checks on calls
10 // to functions in <string.h>.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "InterCheckerAPI.h"
15 #include "clang/AST/OperationKinds.h"
16 #include "clang/Basic/CharInfo.h"
17 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
18 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20 #include "clang/StaticAnalyzer/Core/Checker.h"
21 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
29 #include "llvm/ADT/APSInt.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <functional>
34 #include <optional>
35 
36 using namespace clang;
37 using namespace ento;
38 using namespace std::placeholders;
39 
40 namespace {
41 struct AnyArgExpr {
42   const Expr *Expression;
43   unsigned ArgumentIndex;
44 };
45 struct SourceArgExpr : AnyArgExpr {};
46 struct DestinationArgExpr : AnyArgExpr {};
47 struct SizeArgExpr : AnyArgExpr {};
48 
49 using ErrorMessage = SmallString<128>;
50 enum class AccessKind { write, read };
51 
52 static ErrorMessage createOutOfBoundErrorMsg(StringRef FunctionDescription,
53                                              AccessKind Access) {
54   ErrorMessage Message;
55   llvm::raw_svector_ostream Os(Message);
56 
57   // Function classification like: Memory copy function
58   Os << toUppercase(FunctionDescription.front())
59      << &FunctionDescription.data()[1];
60 
61   if (Access == AccessKind::write) {
62     Os << " overflows the destination buffer";
63   } else { // read access
64     Os << " accesses out-of-bound array element";
65   }
66 
67   return Message;
68 }
69 
70 enum class ConcatFnKind { none = 0, strcat = 1, strlcat = 2 };
71 
72 enum class CharKind { Regular = 0, Wide };
73 constexpr CharKind CK_Regular = CharKind::Regular;
74 constexpr CharKind CK_Wide = CharKind::Wide;
75 
76 static QualType getCharPtrType(ASTContext &Ctx, CharKind CK) {
77   return Ctx.getPointerType(CK == CharKind::Regular ? Ctx.CharTy
78                                                     : Ctx.WideCharTy);
79 }
80 
81 class CStringChecker : public Checker< eval::Call,
82                                          check::PreStmt<DeclStmt>,
83                                          check::LiveSymbols,
84                                          check::DeadSymbols,
85                                          check::RegionChanges
86                                          > {
87   mutable std::unique_ptr<BugType> BT_Null, BT_Bounds, BT_Overlap,
88       BT_NotCString, BT_AdditionOverflow, BT_UninitRead;
89 
90   mutable const char *CurrentFunctionDescription = nullptr;
91 
92 public:
93   /// The filter is used to filter out the diagnostics which are not enabled by
94   /// the user.
95   struct CStringChecksFilter {
96     bool CheckCStringNullArg = false;
97     bool CheckCStringOutOfBounds = false;
98     bool CheckCStringBufferOverlap = false;
99     bool CheckCStringNotNullTerm = false;
100     bool CheckCStringUninitializedRead = false;
101 
102     CheckerNameRef CheckNameCStringNullArg;
103     CheckerNameRef CheckNameCStringOutOfBounds;
104     CheckerNameRef CheckNameCStringBufferOverlap;
105     CheckerNameRef CheckNameCStringNotNullTerm;
106     CheckerNameRef CheckNameCStringUninitializedRead;
107   };
108 
109   CStringChecksFilter Filter;
110 
111   static void *getTag() { static int tag; return &tag; }
112 
113   bool evalCall(const CallEvent &Call, CheckerContext &C) const;
114   void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
115   void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
116   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
117 
118   ProgramStateRef
119     checkRegionChanges(ProgramStateRef state,
120                        const InvalidatedSymbols *,
121                        ArrayRef<const MemRegion *> ExplicitRegions,
122                        ArrayRef<const MemRegion *> Regions,
123                        const LocationContext *LCtx,
124                        const CallEvent *Call) const;
125 
126   using FnCheck = std::function<void(const CStringChecker *, CheckerContext &,
127                                      const CallEvent &)>;
128 
129   CallDescriptionMap<FnCheck> Callbacks = {
130       {{CDM::CLibraryMaybeHardened, {"memcpy"}, 3},
131        std::bind(&CStringChecker::evalMemcpy, _1, _2, _3, CK_Regular)},
132       {{CDM::CLibraryMaybeHardened, {"wmemcpy"}, 3},
133        std::bind(&CStringChecker::evalMemcpy, _1, _2, _3, CK_Wide)},
134       {{CDM::CLibraryMaybeHardened, {"mempcpy"}, 3},
135        std::bind(&CStringChecker::evalMempcpy, _1, _2, _3, CK_Regular)},
136       {{CDM::CLibraryMaybeHardened, {"wmempcpy"}, 3},
137        std::bind(&CStringChecker::evalMempcpy, _1, _2, _3, CK_Wide)},
138       {{CDM::CLibrary, {"memcmp"}, 3},
139        std::bind(&CStringChecker::evalMemcmp, _1, _2, _3, CK_Regular)},
140       {{CDM::CLibrary, {"wmemcmp"}, 3},
141        std::bind(&CStringChecker::evalMemcmp, _1, _2, _3, CK_Wide)},
142       {{CDM::CLibraryMaybeHardened, {"memmove"}, 3},
143        std::bind(&CStringChecker::evalMemmove, _1, _2, _3, CK_Regular)},
144       {{CDM::CLibraryMaybeHardened, {"wmemmove"}, 3},
145        std::bind(&CStringChecker::evalMemmove, _1, _2, _3, CK_Wide)},
146       {{CDM::CLibraryMaybeHardened, {"memset"}, 3},
147        &CStringChecker::evalMemset},
148       {{CDM::CLibrary, {"explicit_memset"}, 3}, &CStringChecker::evalMemset},
149       // FIXME: C23 introduces 'memset_explicit', maybe also model that
150       {{CDM::CLibraryMaybeHardened, {"strcpy"}, 2},
151        &CStringChecker::evalStrcpy},
152       {{CDM::CLibraryMaybeHardened, {"strncpy"}, 3},
153        &CStringChecker::evalStrncpy},
154       {{CDM::CLibraryMaybeHardened, {"stpcpy"}, 2},
155        &CStringChecker::evalStpcpy},
156       {{CDM::CLibraryMaybeHardened, {"strlcpy"}, 3},
157        &CStringChecker::evalStrlcpy},
158       {{CDM::CLibraryMaybeHardened, {"strcat"}, 2},
159        &CStringChecker::evalStrcat},
160       {{CDM::CLibraryMaybeHardened, {"strncat"}, 3},
161        &CStringChecker::evalStrncat},
162       {{CDM::CLibraryMaybeHardened, {"strlcat"}, 3},
163        &CStringChecker::evalStrlcat},
164       {{CDM::CLibraryMaybeHardened, {"strlen"}, 1},
165        &CStringChecker::evalstrLength},
166       {{CDM::CLibrary, {"wcslen"}, 1}, &CStringChecker::evalstrLength},
167       {{CDM::CLibraryMaybeHardened, {"strnlen"}, 2},
168        &CStringChecker::evalstrnLength},
169       {{CDM::CLibrary, {"wcsnlen"}, 2}, &CStringChecker::evalstrnLength},
170       {{CDM::CLibrary, {"strcmp"}, 2}, &CStringChecker::evalStrcmp},
171       {{CDM::CLibrary, {"strncmp"}, 3}, &CStringChecker::evalStrncmp},
172       {{CDM::CLibrary, {"strcasecmp"}, 2}, &CStringChecker::evalStrcasecmp},
173       {{CDM::CLibrary, {"strncasecmp"}, 3}, &CStringChecker::evalStrncasecmp},
174       {{CDM::CLibrary, {"strsep"}, 2}, &CStringChecker::evalStrsep},
175       {{CDM::CLibrary, {"bcopy"}, 3}, &CStringChecker::evalBcopy},
176       {{CDM::CLibrary, {"bcmp"}, 3},
177        std::bind(&CStringChecker::evalMemcmp, _1, _2, _3, CK_Regular)},
178       {{CDM::CLibrary, {"bzero"}, 2}, &CStringChecker::evalBzero},
179       {{CDM::CLibraryMaybeHardened, {"explicit_bzero"}, 2},
180        &CStringChecker::evalBzero},
181 
182       // When recognizing calls to the following variadic functions, we accept
183       // any number of arguments in the call (std::nullopt = accept any
184       // number), but check that in the declaration there are 2 and 3
185       // parameters respectively. (Note that the parameter count does not
186       // include the "...". Calls where the number of arguments is too small
187       // will be discarded by the callback.)
188       {{CDM::CLibraryMaybeHardened, {"sprintf"}, std::nullopt, 2},
189        &CStringChecker::evalSprintf},
190       {{CDM::CLibraryMaybeHardened, {"snprintf"}, std::nullopt, 3},
191        &CStringChecker::evalSnprintf},
192   };
193 
194   // These require a bit of special handling.
195   CallDescription StdCopy{CDM::SimpleFunc, {"std", "copy"}, 3},
196       StdCopyBackward{CDM::SimpleFunc, {"std", "copy_backward"}, 3};
197 
198   FnCheck identifyCall(const CallEvent &Call, CheckerContext &C) const;
199   void evalMemcpy(CheckerContext &C, const CallEvent &Call, CharKind CK) const;
200   void evalMempcpy(CheckerContext &C, const CallEvent &Call, CharKind CK) const;
201   void evalMemmove(CheckerContext &C, const CallEvent &Call, CharKind CK) const;
202   void evalBcopy(CheckerContext &C, const CallEvent &Call) const;
203   void evalCopyCommon(CheckerContext &C, const CallEvent &Call,
204                       ProgramStateRef state, SizeArgExpr Size,
205                       DestinationArgExpr Dest, SourceArgExpr Source,
206                       bool Restricted, bool IsMempcpy, CharKind CK) const;
207 
208   void evalMemcmp(CheckerContext &C, const CallEvent &Call, CharKind CK) const;
209 
210   void evalstrLength(CheckerContext &C, const CallEvent &Call) const;
211   void evalstrnLength(CheckerContext &C, const CallEvent &Call) const;
212   void evalstrLengthCommon(CheckerContext &C, const CallEvent &Call,
213                            bool IsStrnlen = false) const;
214 
215   void evalStrcpy(CheckerContext &C, const CallEvent &Call) const;
216   void evalStrncpy(CheckerContext &C, const CallEvent &Call) const;
217   void evalStpcpy(CheckerContext &C, const CallEvent &Call) const;
218   void evalStrlcpy(CheckerContext &C, const CallEvent &Call) const;
219   void evalStrcpyCommon(CheckerContext &C, const CallEvent &Call,
220                         bool ReturnEnd, bool IsBounded, ConcatFnKind appendK,
221                         bool returnPtr = true) const;
222 
223   void evalStrcat(CheckerContext &C, const CallEvent &Call) const;
224   void evalStrncat(CheckerContext &C, const CallEvent &Call) const;
225   void evalStrlcat(CheckerContext &C, const CallEvent &Call) const;
226 
227   void evalStrcmp(CheckerContext &C, const CallEvent &Call) const;
228   void evalStrncmp(CheckerContext &C, const CallEvent &Call) const;
229   void evalStrcasecmp(CheckerContext &C, const CallEvent &Call) const;
230   void evalStrncasecmp(CheckerContext &C, const CallEvent &Call) const;
231   void evalStrcmpCommon(CheckerContext &C, const CallEvent &Call,
232                         bool IsBounded = false, bool IgnoreCase = false) const;
233 
234   void evalStrsep(CheckerContext &C, const CallEvent &Call) const;
235 
236   void evalStdCopy(CheckerContext &C, const CallEvent &Call) const;
237   void evalStdCopyBackward(CheckerContext &C, const CallEvent &Call) const;
238   void evalStdCopyCommon(CheckerContext &C, const CallEvent &Call) const;
239   void evalMemset(CheckerContext &C, const CallEvent &Call) const;
240   void evalBzero(CheckerContext &C, const CallEvent &Call) const;
241 
242   void evalSprintf(CheckerContext &C, const CallEvent &Call) const;
243   void evalSnprintf(CheckerContext &C, const CallEvent &Call) const;
244   void evalSprintfCommon(CheckerContext &C, const CallEvent &Call,
245                          bool IsBounded) const;
246 
247   // Utility methods
248   std::pair<ProgramStateRef , ProgramStateRef >
249   static assumeZero(CheckerContext &C,
250                     ProgramStateRef state, SVal V, QualType Ty);
251 
252   static ProgramStateRef setCStringLength(ProgramStateRef state,
253                                               const MemRegion *MR,
254                                               SVal strLength);
255   static SVal getCStringLengthForRegion(CheckerContext &C,
256                                         ProgramStateRef &state,
257                                         const Expr *Ex,
258                                         const MemRegion *MR,
259                                         bool hypothetical);
260   SVal getCStringLength(CheckerContext &C,
261                         ProgramStateRef &state,
262                         const Expr *Ex,
263                         SVal Buf,
264                         bool hypothetical = false) const;
265 
266   const StringLiteral *getCStringLiteral(CheckerContext &C,
267                                          ProgramStateRef &state,
268                                          const Expr *expr,
269                                          SVal val) const;
270 
271   /// Invalidate the destination buffer determined by characters copied.
272   static ProgramStateRef
273   invalidateDestinationBufferBySize(CheckerContext &C, ProgramStateRef S,
274                                     const Expr *BufE, ConstCFGElementRef Elem,
275                                     SVal BufV, SVal SizeV, QualType SizeTy);
276 
277   /// Operation never overflows, do not invalidate the super region.
278   static ProgramStateRef invalidateDestinationBufferNeverOverflows(
279       CheckerContext &C, ProgramStateRef S, ConstCFGElementRef Elem, SVal BufV);
280 
281   /// We do not know whether the operation can overflow (e.g. size is unknown),
282   /// invalidate the super region and escape related pointers.
283   static ProgramStateRef invalidateDestinationBufferAlwaysEscapeSuperRegion(
284       CheckerContext &C, ProgramStateRef S, ConstCFGElementRef Elem, SVal BufV);
285 
286   /// Invalidate the source buffer for escaping pointers.
287   static ProgramStateRef invalidateSourceBuffer(CheckerContext &C,
288                                                 ProgramStateRef S,
289                                                 ConstCFGElementRef Elem,
290                                                 SVal BufV);
291 
292   /// @param InvalidationTraitOperations Determine how to invlidate the
293   /// MemRegion by setting the invalidation traits. Return true to cause pointer
294   /// escape, or false otherwise.
295   static ProgramStateRef invalidateBufferAux(
296       CheckerContext &C, ProgramStateRef State, ConstCFGElementRef Elem, SVal V,
297       llvm::function_ref<bool(RegionAndSymbolInvalidationTraits &,
298                               const MemRegion *)>
299           InvalidationTraitOperations);
300 
301   static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
302                               const MemRegion *MR);
303 
304   static bool memsetAux(const Expr *DstBuffer, ConstCFGElementRef Elem,
305                         SVal CharE, const Expr *Size, CheckerContext &C,
306                         ProgramStateRef &State);
307 
308   // Re-usable checks
309   ProgramStateRef checkNonNull(CheckerContext &C, ProgramStateRef State,
310                                AnyArgExpr Arg, SVal l) const;
311   // Check whether the origin region behind \p Element (like the actual array
312   // region \p Element is from) is initialized.
313   ProgramStateRef checkInit(CheckerContext &C, ProgramStateRef state,
314                             AnyArgExpr Buffer, SVal Element, SVal Size) const;
315   ProgramStateRef CheckLocation(CheckerContext &C, ProgramStateRef state,
316                                 AnyArgExpr Buffer, SVal Element,
317                                 AccessKind Access,
318                                 CharKind CK = CharKind::Regular) const;
319   ProgramStateRef CheckBufferAccess(CheckerContext &C, ProgramStateRef State,
320                                     AnyArgExpr Buffer, SizeArgExpr Size,
321                                     AccessKind Access,
322                                     CharKind CK = CharKind::Regular) const;
323   ProgramStateRef CheckOverlap(CheckerContext &C, ProgramStateRef state,
324                                SizeArgExpr Size, AnyArgExpr First,
325                                AnyArgExpr Second,
326                                CharKind CK = CharKind::Regular) const;
327   void emitOverlapBug(CheckerContext &C,
328                       ProgramStateRef state,
329                       const Stmt *First,
330                       const Stmt *Second) const;
331 
332   void emitNullArgBug(CheckerContext &C, ProgramStateRef State, const Stmt *S,
333                       StringRef WarningMsg) const;
334   void emitOutOfBoundsBug(CheckerContext &C, ProgramStateRef State,
335                           const Stmt *S, StringRef WarningMsg) const;
336   void emitNotCStringBug(CheckerContext &C, ProgramStateRef State,
337                          const Stmt *S, StringRef WarningMsg) const;
338   void emitAdditionOverflowBug(CheckerContext &C, ProgramStateRef State) const;
339   void emitUninitializedReadBug(CheckerContext &C, ProgramStateRef State,
340                                 const Expr *E, const MemRegion *R,
341                                 StringRef Msg) const;
342   ProgramStateRef checkAdditionOverflow(CheckerContext &C,
343                                             ProgramStateRef state,
344                                             NonLoc left,
345                                             NonLoc right) const;
346 
347   // Return true if the destination buffer of the copy function may be in bound.
348   // Expects SVal of Size to be positive and unsigned.
349   // Expects SVal of FirstBuf to be a FieldRegion.
350   static bool isFirstBufInBound(CheckerContext &C, ProgramStateRef State,
351                                 SVal BufVal, QualType BufTy, SVal LengthVal,
352                                 QualType LengthTy);
353 };
354 
355 } //end anonymous namespace
356 
357 REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
358 
359 //===----------------------------------------------------------------------===//
360 // Individual checks and utility methods.
361 //===----------------------------------------------------------------------===//
362 
363 std::pair<ProgramStateRef, ProgramStateRef>
364 CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef State, SVal V,
365                            QualType Ty) {
366   std::optional<DefinedSVal> val = V.getAs<DefinedSVal>();
367   if (!val)
368     return std::pair<ProgramStateRef, ProgramStateRef>(State, State);
369 
370   SValBuilder &svalBuilder = C.getSValBuilder();
371   DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
372   return State->assume(svalBuilder.evalEQ(State, *val, zero));
373 }
374 
375 ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
376                                              ProgramStateRef State,
377                                              AnyArgExpr Arg, SVal l) const {
378   // If a previous check has failed, propagate the failure.
379   if (!State)
380     return nullptr;
381 
382   ProgramStateRef stateNull, stateNonNull;
383   std::tie(stateNull, stateNonNull) =
384       assumeZero(C, State, l, Arg.Expression->getType());
385 
386   if (stateNull && !stateNonNull) {
387     if (Filter.CheckCStringNullArg) {
388       SmallString<80> buf;
389       llvm::raw_svector_ostream OS(buf);
390       assert(CurrentFunctionDescription);
391       OS << "Null pointer passed as " << (Arg.ArgumentIndex + 1)
392          << llvm::getOrdinalSuffix(Arg.ArgumentIndex + 1) << " argument to "
393          << CurrentFunctionDescription;
394 
395       emitNullArgBug(C, stateNull, Arg.Expression, OS.str());
396     }
397     return nullptr;
398   }
399 
400   // From here on, assume that the value is non-null.
401   assert(stateNonNull);
402   return stateNonNull;
403 }
404 
405 static std::optional<NonLoc> getIndex(ProgramStateRef State,
406                                       const ElementRegion *ER, CharKind CK) {
407   SValBuilder &SVB = State->getStateManager().getSValBuilder();
408   ASTContext &Ctx = SVB.getContext();
409 
410   if (CK == CharKind::Regular) {
411     if (ER->getValueType() != Ctx.CharTy)
412       return {};
413     return ER->getIndex();
414   }
415 
416   if (ER->getValueType() != Ctx.WideCharTy)
417     return {};
418 
419   QualType SizeTy = Ctx.getSizeType();
420   NonLoc WideSize =
421       SVB.makeIntVal(Ctx.getTypeSizeInChars(Ctx.WideCharTy).getQuantity(),
422                      SizeTy)
423           .castAs<NonLoc>();
424   SVal Offset =
425       SVB.evalBinOpNN(State, BO_Mul, ER->getIndex(), WideSize, SizeTy);
426   if (Offset.isUnknown())
427     return {};
428   return Offset.castAs<NonLoc>();
429 }
430 
431 // Basically 1 -> 1st, 12 -> 12th, etc.
432 static void printIdxWithOrdinalSuffix(llvm::raw_ostream &Os, unsigned Idx) {
433   Os << Idx << llvm::getOrdinalSuffix(Idx);
434 }
435 
436 ProgramStateRef CStringChecker::checkInit(CheckerContext &C,
437                                           ProgramStateRef State,
438                                           AnyArgExpr Buffer, SVal Element,
439                                           SVal Size) const {
440 
441   // If a previous check has failed, propagate the failure.
442   if (!State)
443     return nullptr;
444 
445   const MemRegion *R = Element.getAsRegion();
446   const auto *ER = dyn_cast_or_null<ElementRegion>(R);
447   if (!ER)
448     return State;
449 
450   const auto *SuperR = ER->getSuperRegion()->getAs<TypedValueRegion>();
451   if (!SuperR)
452     return State;
453 
454   // FIXME: We ought to able to check objects as well. Maybe
455   // UninitializedObjectChecker could help?
456   if (!SuperR->getValueType()->isArrayType())
457     return State;
458 
459   SValBuilder &SVB = C.getSValBuilder();
460   ASTContext &Ctx = SVB.getContext();
461 
462   const QualType ElemTy = Ctx.getBaseElementType(SuperR->getValueType());
463   const NonLoc Zero = SVB.makeZeroArrayIndex();
464 
465   std::optional<Loc> FirstElementVal =
466       State->getLValue(ElemTy, Zero, loc::MemRegionVal(SuperR)).getAs<Loc>();
467   if (!FirstElementVal)
468     return State;
469 
470   // Ensure that we wouldn't read uninitialized value.
471   if (Filter.CheckCStringUninitializedRead &&
472       State->getSVal(*FirstElementVal).isUndef()) {
473     llvm::SmallString<258> Buf;
474     llvm::raw_svector_ostream OS(Buf);
475     OS << "The first element of the ";
476     printIdxWithOrdinalSuffix(OS, Buffer.ArgumentIndex + 1);
477     OS << " argument is undefined";
478     emitUninitializedReadBug(C, State, Buffer.Expression,
479                              FirstElementVal->getAsRegion(), OS.str());
480     return nullptr;
481   }
482 
483   // We won't check whether the entire region is fully initialized -- lets just
484   // check that the first and the last element is. So, onto checking the last
485   // element:
486   const QualType IdxTy = SVB.getArrayIndexType();
487 
488   NonLoc ElemSize =
489       SVB.makeIntVal(Ctx.getTypeSizeInChars(ElemTy).getQuantity(), IdxTy)
490           .castAs<NonLoc>();
491 
492   // FIXME: Check that the size arg to the cstring function is divisible by
493   // size of the actual element type?
494 
495   // The type of the argument to the cstring function is either char or wchar,
496   // but thats not the type of the original array (or memory region).
497   // Suppose the following:
498   //   int t[5];
499   //   memcpy(dst, t, sizeof(t) / sizeof(t[0]));
500   // When checking whether t is fully initialized, we see it as char array of
501   // size sizeof(int)*5. If we check the last element as a character, we read
502   // the last byte of an integer, which will be undefined. But just because
503   // that value is undefined, it doesn't mean that the element is uninitialized!
504   // For this reason, we need to retrieve the actual last element with the
505   // correct type.
506 
507   // Divide the size argument to the cstring function by the actual element
508   // type. This value will be size of the array, or the index to the
509   // past-the-end element.
510   std::optional<NonLoc> Offset =
511       SVB.evalBinOpNN(State, clang::BO_Div, Size.castAs<NonLoc>(), ElemSize,
512                       IdxTy)
513           .getAs<NonLoc>();
514 
515   // Retrieve the index of the last element.
516   const NonLoc One = SVB.makeIntVal(1, IdxTy).castAs<NonLoc>();
517   SVal LastIdx = SVB.evalBinOpNN(State, BO_Sub, *Offset, One, IdxTy);
518 
519   if (!Offset)
520     return State;
521 
522   SVal LastElementVal =
523       State->getLValue(ElemTy, LastIdx, loc::MemRegionVal(SuperR));
524   if (!isa<Loc>(LastElementVal))
525     return State;
526 
527   if (Filter.CheckCStringUninitializedRead &&
528       State->getSVal(LastElementVal.castAs<Loc>()).isUndef()) {
529     const llvm::APSInt *IdxInt = LastIdx.getAsInteger();
530     // If we can't get emit a sensible last element index, just bail out --
531     // prefer to emit nothing in favour of emitting garbage quality reports.
532     if (!IdxInt) {
533       C.addSink();
534       return nullptr;
535     }
536     llvm::SmallString<258> Buf;
537     llvm::raw_svector_ostream OS(Buf);
538     OS << "The last accessed element (at index ";
539     OS << IdxInt->getExtValue();
540     OS << ") in the ";
541     printIdxWithOrdinalSuffix(OS, Buffer.ArgumentIndex + 1);
542     OS << " argument is undefined";
543     emitUninitializedReadBug(C, State, Buffer.Expression,
544                              LastElementVal.getAsRegion(), OS.str());
545     return nullptr;
546   }
547   return State;
548 }
549 // FIXME: The root of this logic was copied from the old checker
550 // alpha.security.ArrayBound (which is removed within this commit).
551 // It should be refactored to use the different, more sophisticated bounds
552 // checking logic used by the new checker ``security.ArrayBound``.
553 ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
554                                               ProgramStateRef state,
555                                               AnyArgExpr Buffer, SVal Element,
556                                               AccessKind Access,
557                                               CharKind CK) const {
558 
559   // If a previous check has failed, propagate the failure.
560   if (!state)
561     return nullptr;
562 
563   // Check for out of bound array element access.
564   const MemRegion *R = Element.getAsRegion();
565   if (!R)
566     return state;
567 
568   const auto *ER = dyn_cast<ElementRegion>(R);
569   if (!ER)
570     return state;
571 
572   // Get the index of the accessed element.
573   std::optional<NonLoc> Idx = getIndex(state, ER, CK);
574   if (!Idx)
575     return state;
576 
577   // Get the size of the array.
578   const auto *superReg = cast<SubRegion>(ER->getSuperRegion());
579   DefinedOrUnknownSVal Size =
580       getDynamicExtent(state, superReg, C.getSValBuilder());
581 
582   auto [StInBound, StOutBound] = state->assumeInBoundDual(*Idx, Size);
583   if (StOutBound && !StInBound) {
584     // These checks are either enabled by the CString out-of-bounds checker
585     // explicitly or implicitly by the Malloc checker.
586     // In the latter case we only do modeling but do not emit warning.
587     if (!Filter.CheckCStringOutOfBounds)
588       return nullptr;
589 
590     // Emit a bug report.
591     ErrorMessage Message =
592         createOutOfBoundErrorMsg(CurrentFunctionDescription, Access);
593     emitOutOfBoundsBug(C, StOutBound, Buffer.Expression, Message);
594     return nullptr;
595   }
596 
597   // Array bound check succeeded.  From this point forward the array bound
598   // should always succeed.
599   return StInBound;
600 }
601 
602 ProgramStateRef
603 CStringChecker::CheckBufferAccess(CheckerContext &C, ProgramStateRef State,
604                                   AnyArgExpr Buffer, SizeArgExpr Size,
605                                   AccessKind Access, CharKind CK) const {
606   // If a previous check has failed, propagate the failure.
607   if (!State)
608     return nullptr;
609 
610   SValBuilder &svalBuilder = C.getSValBuilder();
611   ASTContext &Ctx = svalBuilder.getContext();
612 
613   QualType SizeTy = Size.Expression->getType();
614   QualType PtrTy = getCharPtrType(Ctx, CK);
615 
616   // Check that the first buffer is non-null.
617   SVal BufVal = C.getSVal(Buffer.Expression);
618   State = checkNonNull(C, State, Buffer, BufVal);
619   if (!State)
620     return nullptr;
621 
622   // If out-of-bounds checking is turned off, skip the rest.
623   if (!Filter.CheckCStringOutOfBounds)
624     return State;
625 
626   SVal BufStart =
627       svalBuilder.evalCast(BufVal, PtrTy, Buffer.Expression->getType());
628 
629   // Check if the first byte of the buffer is accessible.
630   State = CheckLocation(C, State, Buffer, BufStart, Access, CK);
631 
632   if (!State)
633     return nullptr;
634 
635   // Get the access length and make sure it is known.
636   // FIXME: This assumes the caller has already checked that the access length
637   // is positive. And that it's unsigned.
638   SVal LengthVal = C.getSVal(Size.Expression);
639   std::optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
640   if (!Length)
641     return State;
642 
643   // Compute the offset of the last element to be accessed: size-1.
644   NonLoc One = svalBuilder.makeIntVal(1, SizeTy).castAs<NonLoc>();
645   SVal Offset = svalBuilder.evalBinOpNN(State, BO_Sub, *Length, One, SizeTy);
646   if (Offset.isUnknown())
647     return nullptr;
648   NonLoc LastOffset = Offset.castAs<NonLoc>();
649 
650   // Check that the first buffer is sufficiently long.
651   if (std::optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
652 
653     SVal BufEnd =
654         svalBuilder.evalBinOpLN(State, BO_Add, *BufLoc, LastOffset, PtrTy);
655     State = CheckLocation(C, State, Buffer, BufEnd, Access, CK);
656     if (Access == AccessKind::read)
657       State = checkInit(C, State, Buffer, BufEnd, *Length);
658 
659     // If the buffer isn't large enough, abort.
660     if (!State)
661       return nullptr;
662   }
663 
664   // Large enough or not, return this state!
665   return State;
666 }
667 
668 ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
669                                              ProgramStateRef state,
670                                              SizeArgExpr Size, AnyArgExpr First,
671                                              AnyArgExpr Second,
672                                              CharKind CK) const {
673   if (!Filter.CheckCStringBufferOverlap)
674     return state;
675 
676   // Do a simple check for overlap: if the two arguments are from the same
677   // buffer, see if the end of the first is greater than the start of the second
678   // or vice versa.
679 
680   // If a previous check has failed, propagate the failure.
681   if (!state)
682     return nullptr;
683 
684   ProgramStateRef stateTrue, stateFalse;
685 
686   // Assume different address spaces cannot overlap.
687   if (First.Expression->getType()->getPointeeType().getAddressSpace() !=
688       Second.Expression->getType()->getPointeeType().getAddressSpace())
689     return state;
690 
691   // Get the buffer values and make sure they're known locations.
692   const LocationContext *LCtx = C.getLocationContext();
693   SVal firstVal = state->getSVal(First.Expression, LCtx);
694   SVal secondVal = state->getSVal(Second.Expression, LCtx);
695 
696   std::optional<Loc> firstLoc = firstVal.getAs<Loc>();
697   if (!firstLoc)
698     return state;
699 
700   std::optional<Loc> secondLoc = secondVal.getAs<Loc>();
701   if (!secondLoc)
702     return state;
703 
704   // Are the two values the same?
705   SValBuilder &svalBuilder = C.getSValBuilder();
706   std::tie(stateTrue, stateFalse) =
707       state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
708 
709   if (stateTrue && !stateFalse) {
710     // If the values are known to be equal, that's automatically an overlap.
711     emitOverlapBug(C, stateTrue, First.Expression, Second.Expression);
712     return nullptr;
713   }
714 
715   // assume the two expressions are not equal.
716   assert(stateFalse);
717   state = stateFalse;
718 
719   // Which value comes first?
720   QualType cmpTy = svalBuilder.getConditionType();
721   SVal reverse =
722       svalBuilder.evalBinOpLL(state, BO_GT, *firstLoc, *secondLoc, cmpTy);
723   std::optional<DefinedOrUnknownSVal> reverseTest =
724       reverse.getAs<DefinedOrUnknownSVal>();
725   if (!reverseTest)
726     return state;
727 
728   std::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
729   if (stateTrue) {
730     if (stateFalse) {
731       // If we don't know which one comes first, we can't perform this test.
732       return state;
733     } else {
734       // Switch the values so that firstVal is before secondVal.
735       std::swap(firstLoc, secondLoc);
736 
737       // Switch the Exprs as well, so that they still correspond.
738       std::swap(First, Second);
739     }
740   }
741 
742   // Get the length, and make sure it too is known.
743   SVal LengthVal = state->getSVal(Size.Expression, LCtx);
744   std::optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
745   if (!Length)
746     return state;
747 
748   // Convert the first buffer's start address to char*.
749   // Bail out if the cast fails.
750   ASTContext &Ctx = svalBuilder.getContext();
751   QualType CharPtrTy = getCharPtrType(Ctx, CK);
752   SVal FirstStart =
753       svalBuilder.evalCast(*firstLoc, CharPtrTy, First.Expression->getType());
754   std::optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
755   if (!FirstStartLoc)
756     return state;
757 
758   // Compute the end of the first buffer. Bail out if THAT fails.
759   SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add, *FirstStartLoc,
760                                           *Length, CharPtrTy);
761   std::optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
762   if (!FirstEndLoc)
763     return state;
764 
765   // Is the end of the first buffer past the start of the second buffer?
766   SVal Overlap =
767       svalBuilder.evalBinOpLL(state, BO_GT, *FirstEndLoc, *secondLoc, cmpTy);
768   std::optional<DefinedOrUnknownSVal> OverlapTest =
769       Overlap.getAs<DefinedOrUnknownSVal>();
770   if (!OverlapTest)
771     return state;
772 
773   std::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
774 
775   if (stateTrue && !stateFalse) {
776     // Overlap!
777     emitOverlapBug(C, stateTrue, First.Expression, Second.Expression);
778     return nullptr;
779   }
780 
781   // assume the two expressions don't overlap.
782   assert(stateFalse);
783   return stateFalse;
784 }
785 
786 void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
787                                   const Stmt *First, const Stmt *Second) const {
788   ExplodedNode *N = C.generateErrorNode(state);
789   if (!N)
790     return;
791 
792   if (!BT_Overlap)
793     BT_Overlap.reset(new BugType(Filter.CheckNameCStringBufferOverlap,
794                                  categories::UnixAPI, "Improper arguments"));
795 
796   // Generate a report for this bug.
797   auto report = std::make_unique<PathSensitiveBugReport>(
798       *BT_Overlap, "Arguments must not be overlapping buffers", N);
799   report->addRange(First->getSourceRange());
800   report->addRange(Second->getSourceRange());
801 
802   C.emitReport(std::move(report));
803 }
804 
805 void CStringChecker::emitNullArgBug(CheckerContext &C, ProgramStateRef State,
806                                     const Stmt *S, StringRef WarningMsg) const {
807   if (ExplodedNode *N = C.generateErrorNode(State)) {
808     if (!BT_Null) {
809       // FIXME: This call uses the string constant 'categories::UnixAPI' as the
810       // description of the bug; it should be replaced by a real description.
811       BT_Null.reset(
812           new BugType(Filter.CheckNameCStringNullArg, categories::UnixAPI));
813     }
814 
815     auto Report =
816         std::make_unique<PathSensitiveBugReport>(*BT_Null, WarningMsg, N);
817     Report->addRange(S->getSourceRange());
818     if (const auto *Ex = dyn_cast<Expr>(S))
819       bugreporter::trackExpressionValue(N, Ex, *Report);
820     C.emitReport(std::move(Report));
821   }
822 }
823 
824 void CStringChecker::emitUninitializedReadBug(CheckerContext &C,
825                                               ProgramStateRef State,
826                                               const Expr *E, const MemRegion *R,
827                                               StringRef Msg) const {
828   if (ExplodedNode *N = C.generateErrorNode(State)) {
829     if (!BT_UninitRead)
830       BT_UninitRead.reset(new BugType(Filter.CheckNameCStringUninitializedRead,
831                                       "Accessing unitialized/garbage values"));
832 
833     auto Report =
834         std::make_unique<PathSensitiveBugReport>(*BT_UninitRead, Msg, N);
835     Report->addNote("Other elements might also be undefined",
836                     Report->getLocation());
837     Report->addRange(E->getSourceRange());
838     bugreporter::trackExpressionValue(N, E, *Report);
839     Report->addVisitor<NoStoreFuncVisitor>(R->castAs<SubRegion>());
840     C.emitReport(std::move(Report));
841   }
842 }
843 
844 void CStringChecker::emitOutOfBoundsBug(CheckerContext &C,
845                                         ProgramStateRef State, const Stmt *S,
846                                         StringRef WarningMsg) const {
847   if (ExplodedNode *N = C.generateErrorNode(State)) {
848     if (!BT_Bounds)
849       BT_Bounds.reset(new BugType(Filter.CheckCStringOutOfBounds
850                                       ? Filter.CheckNameCStringOutOfBounds
851                                       : Filter.CheckNameCStringNullArg,
852                                   "Out-of-bound array access"));
853 
854     // FIXME: It would be nice to eventually make this diagnostic more clear,
855     // e.g., by referencing the original declaration or by saying *why* this
856     // reference is outside the range.
857     auto Report =
858         std::make_unique<PathSensitiveBugReport>(*BT_Bounds, WarningMsg, N);
859     Report->addRange(S->getSourceRange());
860     C.emitReport(std::move(Report));
861   }
862 }
863 
864 void CStringChecker::emitNotCStringBug(CheckerContext &C, ProgramStateRef State,
865                                        const Stmt *S,
866                                        StringRef WarningMsg) const {
867   if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) {
868     if (!BT_NotCString) {
869       // FIXME: This call uses the string constant 'categories::UnixAPI' as the
870       // description of the bug; it should be replaced by a real description.
871       BT_NotCString.reset(
872           new BugType(Filter.CheckNameCStringNotNullTerm, categories::UnixAPI));
873     }
874 
875     auto Report =
876         std::make_unique<PathSensitiveBugReport>(*BT_NotCString, WarningMsg, N);
877 
878     Report->addRange(S->getSourceRange());
879     C.emitReport(std::move(Report));
880   }
881 }
882 
883 void CStringChecker::emitAdditionOverflowBug(CheckerContext &C,
884                                              ProgramStateRef State) const {
885   if (ExplodedNode *N = C.generateErrorNode(State)) {
886     if (!BT_AdditionOverflow) {
887       // FIXME: This call uses the word "API" as the description of the bug;
888       // it should be replaced by a better error message (if this unlikely
889       // situation continues to exist as a separate bug type).
890       BT_AdditionOverflow.reset(
891           new BugType(Filter.CheckNameCStringOutOfBounds, "API"));
892     }
893 
894     // This isn't a great error message, but this should never occur in real
895     // code anyway -- you'd have to create a buffer longer than a size_t can
896     // represent, which is sort of a contradiction.
897     const char *WarningMsg =
898         "This expression will create a string whose length is too big to "
899         "be represented as a size_t";
900 
901     auto Report = std::make_unique<PathSensitiveBugReport>(*BT_AdditionOverflow,
902                                                            WarningMsg, N);
903     C.emitReport(std::move(Report));
904   }
905 }
906 
907 ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
908                                                      ProgramStateRef state,
909                                                      NonLoc left,
910                                                      NonLoc right) const {
911   // If out-of-bounds checking is turned off, skip the rest.
912   if (!Filter.CheckCStringOutOfBounds)
913     return state;
914 
915   // If a previous check has failed, propagate the failure.
916   if (!state)
917     return nullptr;
918 
919   SValBuilder &svalBuilder = C.getSValBuilder();
920   BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
921 
922   QualType sizeTy = svalBuilder.getContext().getSizeType();
923   const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
924   NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
925 
926   SVal maxMinusRight;
927   if (isa<nonloc::ConcreteInt>(right)) {
928     maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
929                                                  sizeTy);
930   } else {
931     // Try switching the operands. (The order of these two assignments is
932     // important!)
933     maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
934                                             sizeTy);
935     left = right;
936   }
937 
938   if (std::optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
939     QualType cmpTy = svalBuilder.getConditionType();
940     // If left > max - right, we have an overflow.
941     SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
942                                                 *maxMinusRightNL, cmpTy);
943 
944     ProgramStateRef stateOverflow, stateOkay;
945     std::tie(stateOverflow, stateOkay) =
946       state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
947 
948     if (stateOverflow && !stateOkay) {
949       // We have an overflow. Emit a bug report.
950       emitAdditionOverflowBug(C, stateOverflow);
951       return nullptr;
952     }
953 
954     // From now on, assume an overflow didn't occur.
955     assert(stateOkay);
956     state = stateOkay;
957   }
958 
959   return state;
960 }
961 
962 ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
963                                                 const MemRegion *MR,
964                                                 SVal strLength) {
965   assert(!strLength.isUndef() && "Attempt to set an undefined string length");
966 
967   MR = MR->StripCasts();
968 
969   switch (MR->getKind()) {
970   case MemRegion::StringRegionKind:
971     // FIXME: This can happen if we strcpy() into a string region. This is
972     // undefined [C99 6.4.5p6], but we should still warn about it.
973     return state;
974 
975   case MemRegion::SymbolicRegionKind:
976   case MemRegion::AllocaRegionKind:
977   case MemRegion::NonParamVarRegionKind:
978   case MemRegion::ParamVarRegionKind:
979   case MemRegion::FieldRegionKind:
980   case MemRegion::ObjCIvarRegionKind:
981     // These are the types we can currently track string lengths for.
982     break;
983 
984   case MemRegion::ElementRegionKind:
985     // FIXME: Handle element regions by upper-bounding the parent region's
986     // string length.
987     return state;
988 
989   default:
990     // Other regions (mostly non-data) can't have a reliable C string length.
991     // For now, just ignore the change.
992     // FIXME: These are rare but not impossible. We should output some kind of
993     // warning for things like strcpy((char[]){'a', 0}, "b");
994     return state;
995   }
996 
997   if (strLength.isUnknown())
998     return state->remove<CStringLength>(MR);
999 
1000   return state->set<CStringLength>(MR, strLength);
1001 }
1002 
1003 SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
1004                                                ProgramStateRef &state,
1005                                                const Expr *Ex,
1006                                                const MemRegion *MR,
1007                                                bool hypothetical) {
1008   if (!hypothetical) {
1009     // If there's a recorded length, go ahead and return it.
1010     const SVal *Recorded = state->get<CStringLength>(MR);
1011     if (Recorded)
1012       return *Recorded;
1013   }
1014 
1015   // Otherwise, get a new symbol and update the state.
1016   SValBuilder &svalBuilder = C.getSValBuilder();
1017   QualType sizeTy = svalBuilder.getContext().getSizeType();
1018   SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
1019                                                     MR, Ex, sizeTy,
1020                                                     C.getLocationContext(),
1021                                                     C.blockCount());
1022 
1023   if (!hypothetical) {
1024     if (std::optional<NonLoc> strLn = strLength.getAs<NonLoc>()) {
1025       // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4
1026       BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
1027       const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
1028       llvm::APSInt fourInt = APSIntType(maxValInt).getValue(4);
1029       std::optional<APSIntPtr> maxLengthInt =
1030           BVF.evalAPSInt(BO_Div, maxValInt, fourInt);
1031       NonLoc maxLength = svalBuilder.makeIntVal(*maxLengthInt);
1032       SVal evalLength = svalBuilder.evalBinOpNN(state, BO_LE, *strLn, maxLength,
1033                                                 svalBuilder.getConditionType());
1034       state = state->assume(evalLength.castAs<DefinedOrUnknownSVal>(), true);
1035     }
1036     state = state->set<CStringLength>(MR, strLength);
1037   }
1038 
1039   return strLength;
1040 }
1041 
1042 SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
1043                                       const Expr *Ex, SVal Buf,
1044                                       bool hypothetical) const {
1045   const MemRegion *MR = Buf.getAsRegion();
1046   if (!MR) {
1047     // If we can't get a region, see if it's something we /know/ isn't a
1048     // C string. In the context of locations, the only time we can issue such
1049     // a warning is for labels.
1050     if (std::optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
1051       if (Filter.CheckCStringNotNullTerm) {
1052         SmallString<120> buf;
1053         llvm::raw_svector_ostream os(buf);
1054         assert(CurrentFunctionDescription);
1055         os << "Argument to " << CurrentFunctionDescription
1056            << " is the address of the label '" << Label->getLabel()->getName()
1057            << "', which is not a null-terminated string";
1058 
1059         emitNotCStringBug(C, state, Ex, os.str());
1060       }
1061       return UndefinedVal();
1062     }
1063 
1064     // If it's not a region and not a label, give up.
1065     return UnknownVal();
1066   }
1067 
1068   // If we have a region, strip casts from it and see if we can figure out
1069   // its length. For anything we can't figure out, just return UnknownVal.
1070   MR = MR->StripCasts();
1071 
1072   switch (MR->getKind()) {
1073   case MemRegion::StringRegionKind: {
1074     // Modifying the contents of string regions is undefined [C99 6.4.5p6],
1075     // so we can assume that the byte length is the correct C string length.
1076     SValBuilder &svalBuilder = C.getSValBuilder();
1077     QualType sizeTy = svalBuilder.getContext().getSizeType();
1078     const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
1079     return svalBuilder.makeIntVal(strLit->getLength(), sizeTy);
1080   }
1081   case MemRegion::NonParamVarRegionKind: {
1082     // If we have a global constant with a string literal initializer,
1083     // compute the initializer's length.
1084     const VarDecl *Decl = cast<NonParamVarRegion>(MR)->getDecl();
1085     if (Decl->getType().isConstQualified() && Decl->hasGlobalStorage()) {
1086       if (const Expr *Init = Decl->getInit()) {
1087         if (auto *StrLit = dyn_cast<StringLiteral>(Init)) {
1088           SValBuilder &SvalBuilder = C.getSValBuilder();
1089           QualType SizeTy = SvalBuilder.getContext().getSizeType();
1090           return SvalBuilder.makeIntVal(StrLit->getLength(), SizeTy);
1091         }
1092       }
1093     }
1094     [[fallthrough]];
1095   }
1096   case MemRegion::SymbolicRegionKind:
1097   case MemRegion::AllocaRegionKind:
1098   case MemRegion::ParamVarRegionKind:
1099   case MemRegion::FieldRegionKind:
1100   case MemRegion::ObjCIvarRegionKind:
1101     return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
1102   case MemRegion::CompoundLiteralRegionKind:
1103     // FIXME: Can we track this? Is it necessary?
1104     return UnknownVal();
1105   case MemRegion::ElementRegionKind:
1106     // FIXME: How can we handle this? It's not good enough to subtract the
1107     // offset from the base string length; consider "123\x00567" and &a[5].
1108     return UnknownVal();
1109   default:
1110     // Other regions (mostly non-data) can't have a reliable C string length.
1111     // In this case, an error is emitted and UndefinedVal is returned.
1112     // The caller should always be prepared to handle this case.
1113     if (Filter.CheckCStringNotNullTerm) {
1114       SmallString<120> buf;
1115       llvm::raw_svector_ostream os(buf);
1116 
1117       assert(CurrentFunctionDescription);
1118       os << "Argument to " << CurrentFunctionDescription << " is ";
1119 
1120       if (SummarizeRegion(os, C.getASTContext(), MR))
1121         os << ", which is not a null-terminated string";
1122       else
1123         os << "not a null-terminated string";
1124 
1125       emitNotCStringBug(C, state, Ex, os.str());
1126     }
1127     return UndefinedVal();
1128   }
1129 }
1130 
1131 const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
1132   ProgramStateRef &state, const Expr *expr, SVal val) const {
1133 
1134   // Get the memory region pointed to by the val.
1135   const MemRegion *bufRegion = val.getAsRegion();
1136   if (!bufRegion)
1137     return nullptr;
1138 
1139   // Strip casts off the memory region.
1140   bufRegion = bufRegion->StripCasts();
1141 
1142   // Cast the memory region to a string region.
1143   const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
1144   if (!strRegion)
1145     return nullptr;
1146 
1147   // Return the actual string in the string region.
1148   return strRegion->getStringLiteral();
1149 }
1150 
1151 bool CStringChecker::isFirstBufInBound(CheckerContext &C, ProgramStateRef State,
1152                                        SVal BufVal, QualType BufTy,
1153                                        SVal LengthVal, QualType LengthTy) {
1154   // If we do not know that the buffer is long enough we return 'true'.
1155   // Otherwise the parent region of this field region would also get
1156   // invalidated, which would lead to warnings based on an unknown state.
1157 
1158   if (LengthVal.isUnknown())
1159     return false;
1160 
1161   // Originally copied from CheckBufferAccess and CheckLocation.
1162   SValBuilder &SB = C.getSValBuilder();
1163   ASTContext &Ctx = C.getASTContext();
1164 
1165   QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
1166 
1167   std::optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
1168   if (!Length)
1169     return true; // cf top comment.
1170 
1171   // Compute the offset of the last element to be accessed: size-1.
1172   NonLoc One = SB.makeIntVal(1, LengthTy).castAs<NonLoc>();
1173   SVal Offset = SB.evalBinOpNN(State, BO_Sub, *Length, One, LengthTy);
1174   if (Offset.isUnknown())
1175     return true; // cf top comment
1176   NonLoc LastOffset = Offset.castAs<NonLoc>();
1177 
1178   // Check that the first buffer is sufficiently long.
1179   SVal BufStart = SB.evalCast(BufVal, PtrTy, BufTy);
1180   std::optional<Loc> BufLoc = BufStart.getAs<Loc>();
1181   if (!BufLoc)
1182     return true; // cf top comment.
1183 
1184   SVal BufEnd = SB.evalBinOpLN(State, BO_Add, *BufLoc, LastOffset, PtrTy);
1185 
1186   // Check for out of bound array element access.
1187   const MemRegion *R = BufEnd.getAsRegion();
1188   if (!R)
1189     return true; // cf top comment.
1190 
1191   const ElementRegion *ER = dyn_cast<ElementRegion>(R);
1192   if (!ER)
1193     return true; // cf top comment.
1194 
1195   // FIXME: Does this crash when a non-standard definition
1196   // of a library function is encountered?
1197   assert(ER->getValueType() == C.getASTContext().CharTy &&
1198          "isFirstBufInBound should only be called with char* ElementRegions");
1199 
1200   // Get the size of the array.
1201   const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
1202   DefinedOrUnknownSVal SizeDV = getDynamicExtent(State, superReg, SB);
1203 
1204   // Get the index of the accessed element.
1205   DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
1206 
1207   ProgramStateRef StInBound = State->assumeInBound(Idx, SizeDV, true);
1208 
1209   return static_cast<bool>(StInBound);
1210 }
1211 
1212 ProgramStateRef CStringChecker::invalidateDestinationBufferBySize(
1213     CheckerContext &C, ProgramStateRef S, const Expr *BufE,
1214     ConstCFGElementRef Elem, SVal BufV, SVal SizeV, QualType SizeTy) {
1215   auto InvalidationTraitOperations =
1216       [&C, S, BufTy = BufE->getType(), BufV, SizeV,
1217        SizeTy](RegionAndSymbolInvalidationTraits &ITraits, const MemRegion *R) {
1218         // If destination buffer is a field region and access is in bound, do
1219         // not invalidate its super region.
1220         if (MemRegion::FieldRegionKind == R->getKind() &&
1221             isFirstBufInBound(C, S, BufV, BufTy, SizeV, SizeTy)) {
1222           ITraits.setTrait(
1223               R,
1224               RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
1225         }
1226         return false;
1227       };
1228 
1229   return invalidateBufferAux(C, S, Elem, BufV, InvalidationTraitOperations);
1230 }
1231 
1232 ProgramStateRef
1233 CStringChecker::invalidateDestinationBufferAlwaysEscapeSuperRegion(
1234     CheckerContext &C, ProgramStateRef S, ConstCFGElementRef Elem, SVal BufV) {
1235   auto InvalidationTraitOperations = [](RegionAndSymbolInvalidationTraits &,
1236                                         const MemRegion *R) {
1237     return isa<FieldRegion>(R);
1238   };
1239 
1240   return invalidateBufferAux(C, S, Elem, BufV, InvalidationTraitOperations);
1241 }
1242 
1243 ProgramStateRef CStringChecker::invalidateDestinationBufferNeverOverflows(
1244     CheckerContext &C, ProgramStateRef S, ConstCFGElementRef Elem, SVal BufV) {
1245   auto InvalidationTraitOperations =
1246       [](RegionAndSymbolInvalidationTraits &ITraits, const MemRegion *R) {
1247         if (MemRegion::FieldRegionKind == R->getKind())
1248           ITraits.setTrait(
1249               R,
1250               RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
1251         return false;
1252       };
1253 
1254   return invalidateBufferAux(C, S, Elem, BufV, InvalidationTraitOperations);
1255 }
1256 
1257 ProgramStateRef CStringChecker::invalidateSourceBuffer(CheckerContext &C,
1258                                                        ProgramStateRef S,
1259                                                        ConstCFGElementRef Elem,
1260                                                        SVal BufV) {
1261   auto InvalidationTraitOperations =
1262       [](RegionAndSymbolInvalidationTraits &ITraits, const MemRegion *R) {
1263         ITraits.setTrait(
1264             R->getBaseRegion(),
1265             RegionAndSymbolInvalidationTraits::TK_PreserveContents);
1266         ITraits.setTrait(R,
1267                          RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
1268         return true;
1269       };
1270 
1271   return invalidateBufferAux(C, S, Elem, BufV, InvalidationTraitOperations);
1272 }
1273 
1274 ProgramStateRef CStringChecker::invalidateBufferAux(
1275     CheckerContext &C, ProgramStateRef State, ConstCFGElementRef Elem, SVal V,
1276     llvm::function_ref<bool(RegionAndSymbolInvalidationTraits &,
1277                             const MemRegion *)>
1278         InvalidationTraitOperations) {
1279   std::optional<Loc> L = V.getAs<Loc>();
1280   if (!L)
1281     return State;
1282 
1283   // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
1284   // some assumptions about the value that CFRefCount can't. Even so, it should
1285   // probably be refactored.
1286   if (std::optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
1287     const MemRegion *R = MR->getRegion()->StripCasts();
1288 
1289     // Are we dealing with an ElementRegion?  If so, we should be invalidating
1290     // the super-region.
1291     if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
1292       R = ER->getSuperRegion();
1293       // FIXME: What about layers of ElementRegions?
1294     }
1295 
1296     // Invalidate this region.
1297     const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1298     RegionAndSymbolInvalidationTraits ITraits;
1299     bool CausesPointerEscape = InvalidationTraitOperations(ITraits, R);
1300 
1301     return State->invalidateRegions(R, Elem, C.blockCount(), LCtx,
1302                                     CausesPointerEscape, nullptr, nullptr,
1303                                     &ITraits);
1304   }
1305 
1306   // If we have a non-region value by chance, just remove the binding.
1307   // FIXME: is this necessary or correct? This handles the non-Region
1308   //  cases.  Is it ever valid to store to these?
1309   return State->killBinding(*L);
1310 }
1311 
1312 bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
1313                                      const MemRegion *MR) {
1314   switch (MR->getKind()) {
1315   case MemRegion::FunctionCodeRegionKind: {
1316     if (const auto *FD = cast<FunctionCodeRegion>(MR)->getDecl())
1317       os << "the address of the function '" << *FD << '\'';
1318     else
1319       os << "the address of a function";
1320     return true;
1321   }
1322   case MemRegion::BlockCodeRegionKind:
1323     os << "block text";
1324     return true;
1325   case MemRegion::BlockDataRegionKind:
1326     os << "a block";
1327     return true;
1328   case MemRegion::CXXThisRegionKind:
1329   case MemRegion::CXXTempObjectRegionKind:
1330     os << "a C++ temp object of type "
1331        << cast<TypedValueRegion>(MR)->getValueType();
1332     return true;
1333   case MemRegion::NonParamVarRegionKind:
1334     os << "a variable of type" << cast<TypedValueRegion>(MR)->getValueType();
1335     return true;
1336   case MemRegion::ParamVarRegionKind:
1337     os << "a parameter of type" << cast<TypedValueRegion>(MR)->getValueType();
1338     return true;
1339   case MemRegion::FieldRegionKind:
1340     os << "a field of type " << cast<TypedValueRegion>(MR)->getValueType();
1341     return true;
1342   case MemRegion::ObjCIvarRegionKind:
1343     os << "an instance variable of type "
1344        << cast<TypedValueRegion>(MR)->getValueType();
1345     return true;
1346   default:
1347     return false;
1348   }
1349 }
1350 
1351 bool CStringChecker::memsetAux(const Expr *DstBuffer, ConstCFGElementRef Elem,
1352                                SVal CharVal, const Expr *Size,
1353                                CheckerContext &C, ProgramStateRef &State) {
1354   SVal MemVal = C.getSVal(DstBuffer);
1355   SVal SizeVal = C.getSVal(Size);
1356   const MemRegion *MR = MemVal.getAsRegion();
1357   if (!MR)
1358     return false;
1359 
1360   // We're about to model memset by producing a "default binding" in the Store.
1361   // Our current implementation - RegionStore - doesn't support default bindings
1362   // that don't cover the whole base region. So we should first get the offset
1363   // and the base region to figure out whether the offset of buffer is 0.
1364   RegionOffset Offset = MR->getAsOffset();
1365   const MemRegion *BR = Offset.getRegion();
1366 
1367   std::optional<NonLoc> SizeNL = SizeVal.getAs<NonLoc>();
1368   if (!SizeNL)
1369     return false;
1370 
1371   SValBuilder &svalBuilder = C.getSValBuilder();
1372   ASTContext &Ctx = C.getASTContext();
1373 
1374   // void *memset(void *dest, int ch, size_t count);
1375   // For now we can only handle the case of offset is 0 and concrete char value.
1376   if (Offset.isValid() && !Offset.hasSymbolicOffset() &&
1377       Offset.getOffset() == 0) {
1378     // Get the base region's size.
1379     DefinedOrUnknownSVal SizeDV = getDynamicExtent(State, BR, svalBuilder);
1380 
1381     ProgramStateRef StateWholeReg, StateNotWholeReg;
1382     std::tie(StateWholeReg, StateNotWholeReg) =
1383         State->assume(svalBuilder.evalEQ(State, SizeDV, *SizeNL));
1384 
1385     // With the semantic of 'memset()', we should convert the CharVal to
1386     // unsigned char.
1387     CharVal = svalBuilder.evalCast(CharVal, Ctx.UnsignedCharTy, Ctx.IntTy);
1388 
1389     ProgramStateRef StateNullChar, StateNonNullChar;
1390     std::tie(StateNullChar, StateNonNullChar) =
1391         assumeZero(C, State, CharVal, Ctx.UnsignedCharTy);
1392 
1393     if (StateWholeReg && !StateNotWholeReg && StateNullChar &&
1394         !StateNonNullChar) {
1395       // If the 'memset()' acts on the whole region of destination buffer and
1396       // the value of the second argument of 'memset()' is zero, bind the second
1397       // argument's value to the destination buffer with 'default binding'.
1398       // FIXME: Since there is no perfect way to bind the non-zero character, we
1399       // can only deal with zero value here. In the future, we need to deal with
1400       // the binding of non-zero value in the case of whole region.
1401       State = State->bindDefaultZero(svalBuilder.makeLoc(BR),
1402                                      C.getLocationContext());
1403     } else {
1404       // If the destination buffer's extent is not equal to the value of
1405       // third argument, just invalidate buffer.
1406       State = invalidateDestinationBufferBySize(
1407           C, State, DstBuffer, Elem, MemVal, SizeVal, Size->getType());
1408     }
1409 
1410     if (StateNullChar && !StateNonNullChar) {
1411       // If the value of the second argument of 'memset()' is zero, set the
1412       // string length of destination buffer to 0 directly.
1413       State = setCStringLength(State, MR,
1414                                svalBuilder.makeZeroVal(Ctx.getSizeType()));
1415     } else if (!StateNullChar && StateNonNullChar) {
1416       SVal NewStrLen = svalBuilder.getMetadataSymbolVal(
1417           CStringChecker::getTag(), MR, DstBuffer, Ctx.getSizeType(),
1418           C.getLocationContext(), C.blockCount());
1419 
1420       // If the value of second argument is not zero, then the string length
1421       // is at least the size argument.
1422       SVal NewStrLenGESize = svalBuilder.evalBinOp(
1423           State, BO_GE, NewStrLen, SizeVal, svalBuilder.getConditionType());
1424 
1425       State = setCStringLength(
1426           State->assume(NewStrLenGESize.castAs<DefinedOrUnknownSVal>(), true),
1427           MR, NewStrLen);
1428     }
1429   } else {
1430     // If the offset is not zero and char value is not concrete, we can do
1431     // nothing but invalidate the buffer.
1432     State = invalidateDestinationBufferBySize(C, State, DstBuffer, Elem, MemVal,
1433                                               SizeVal, Size->getType());
1434   }
1435   return true;
1436 }
1437 
1438 //===----------------------------------------------------------------------===//
1439 // evaluation of individual function calls.
1440 //===----------------------------------------------------------------------===//
1441 
1442 void CStringChecker::evalCopyCommon(CheckerContext &C, const CallEvent &Call,
1443                                     ProgramStateRef state, SizeArgExpr Size,
1444                                     DestinationArgExpr Dest,
1445                                     SourceArgExpr Source, bool Restricted,
1446                                     bool IsMempcpy, CharKind CK) const {
1447   CurrentFunctionDescription = "memory copy function";
1448 
1449   // See if the size argument is zero.
1450   const LocationContext *LCtx = C.getLocationContext();
1451   SVal sizeVal = state->getSVal(Size.Expression, LCtx);
1452   QualType sizeTy = Size.Expression->getType();
1453 
1454   ProgramStateRef stateZeroSize, stateNonZeroSize;
1455   std::tie(stateZeroSize, stateNonZeroSize) =
1456       assumeZero(C, state, sizeVal, sizeTy);
1457 
1458   // Get the value of the Dest.
1459   SVal destVal = state->getSVal(Dest.Expression, LCtx);
1460 
1461   // If the size is zero, there won't be any actual memory access, so
1462   // just bind the return value to the destination buffer and return.
1463   if (stateZeroSize && !stateNonZeroSize) {
1464     stateZeroSize =
1465         stateZeroSize->BindExpr(Call.getOriginExpr(), LCtx, destVal);
1466     C.addTransition(stateZeroSize);
1467     return;
1468   }
1469 
1470   // If the size can be nonzero, we have to check the other arguments.
1471   if (stateNonZeroSize) {
1472     // TODO: If Size is tainted and we cannot prove that it is smaller or equal
1473     // to the size of the destination buffer, then emit a warning
1474     // that an attacker may provoke a buffer overflow error.
1475     state = stateNonZeroSize;
1476 
1477     // Ensure the destination is not null. If it is NULL there will be a
1478     // NULL pointer dereference.
1479     state = checkNonNull(C, state, Dest, destVal);
1480     if (!state)
1481       return;
1482 
1483     // Get the value of the Src.
1484     SVal srcVal = state->getSVal(Source.Expression, LCtx);
1485 
1486     // Ensure the source is not null. If it is NULL there will be a
1487     // NULL pointer dereference.
1488     state = checkNonNull(C, state, Source, srcVal);
1489     if (!state)
1490       return;
1491 
1492     // Ensure the accesses are valid and that the buffers do not overlap.
1493     state = CheckBufferAccess(C, state, Dest, Size, AccessKind::write, CK);
1494     state = CheckBufferAccess(C, state, Source, Size, AccessKind::read, CK);
1495 
1496     if (Restricted)
1497       state = CheckOverlap(C, state, Size, Dest, Source, CK);
1498 
1499     if (!state)
1500       return;
1501 
1502     // If this is mempcpy, get the byte after the last byte copied and
1503     // bind the expr.
1504     if (IsMempcpy) {
1505       // Get the byte after the last byte copied.
1506       SValBuilder &SvalBuilder = C.getSValBuilder();
1507       ASTContext &Ctx = SvalBuilder.getContext();
1508       QualType CharPtrTy = getCharPtrType(Ctx, CK);
1509       SVal DestRegCharVal =
1510           SvalBuilder.evalCast(destVal, CharPtrTy, Dest.Expression->getType());
1511       SVal lastElement = C.getSValBuilder().evalBinOp(
1512           state, BO_Add, DestRegCharVal, sizeVal, Dest.Expression->getType());
1513       // If we don't know how much we copied, we can at least
1514       // conjure a return value for later.
1515       if (lastElement.isUnknown())
1516         lastElement = C.getSValBuilder().conjureSymbolVal(Call, C.blockCount());
1517 
1518       // The byte after the last byte copied is the return value.
1519       state = state->BindExpr(Call.getOriginExpr(), LCtx, lastElement);
1520     } else {
1521       // All other copies return the destination buffer.
1522       // (Well, bcopy() has a void return type, but this won't hurt.)
1523       state = state->BindExpr(Call.getOriginExpr(), LCtx, destVal);
1524     }
1525 
1526     // Invalidate the destination (regular invalidation without pointer-escaping
1527     // the address of the top-level region).
1528     // FIXME: Even if we can't perfectly model the copy, we should see if we
1529     // can use LazyCompoundVals to copy the source values into the destination.
1530     // This would probably remove any existing bindings past the end of the
1531     // copied region, but that's still an improvement over blank invalidation.
1532     state = invalidateDestinationBufferBySize(
1533         C, state, Dest.Expression, Call.getCFGElementRef(),
1534         C.getSVal(Dest.Expression), sizeVal, Size.Expression->getType());
1535 
1536     // Invalidate the source (const-invalidation without const-pointer-escaping
1537     // the address of the top-level region).
1538     state = invalidateSourceBuffer(C, state, Call.getCFGElementRef(),
1539                                    C.getSVal(Source.Expression));
1540 
1541     C.addTransition(state);
1542   }
1543 }
1544 
1545 void CStringChecker::evalMemcpy(CheckerContext &C, const CallEvent &Call,
1546                                 CharKind CK) const {
1547   // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
1548   // The return value is the address of the destination buffer.
1549   DestinationArgExpr Dest = {{Call.getArgExpr(0), 0}};
1550   SourceArgExpr Src = {{Call.getArgExpr(1), 1}};
1551   SizeArgExpr Size = {{Call.getArgExpr(2), 2}};
1552 
1553   ProgramStateRef State = C.getState();
1554 
1555   constexpr bool IsRestricted = true;
1556   constexpr bool IsMempcpy = false;
1557   evalCopyCommon(C, Call, State, Size, Dest, Src, IsRestricted, IsMempcpy, CK);
1558 }
1559 
1560 void CStringChecker::evalMempcpy(CheckerContext &C, const CallEvent &Call,
1561                                  CharKind CK) const {
1562   // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
1563   // The return value is a pointer to the byte following the last written byte.
1564   DestinationArgExpr Dest = {{Call.getArgExpr(0), 0}};
1565   SourceArgExpr Src = {{Call.getArgExpr(1), 1}};
1566   SizeArgExpr Size = {{Call.getArgExpr(2), 2}};
1567 
1568   constexpr bool IsRestricted = true;
1569   constexpr bool IsMempcpy = true;
1570   evalCopyCommon(C, Call, C.getState(), Size, Dest, Src, IsRestricted,
1571                  IsMempcpy, CK);
1572 }
1573 
1574 void CStringChecker::evalMemmove(CheckerContext &C, const CallEvent &Call,
1575                                  CharKind CK) const {
1576   // void *memmove(void *dst, const void *src, size_t n);
1577   // The return value is the address of the destination buffer.
1578   DestinationArgExpr Dest = {{Call.getArgExpr(0), 0}};
1579   SourceArgExpr Src = {{Call.getArgExpr(1), 1}};
1580   SizeArgExpr Size = {{Call.getArgExpr(2), 2}};
1581 
1582   constexpr bool IsRestricted = false;
1583   constexpr bool IsMempcpy = false;
1584   evalCopyCommon(C, Call, C.getState(), Size, Dest, Src, IsRestricted,
1585                  IsMempcpy, CK);
1586 }
1587 
1588 void CStringChecker::evalBcopy(CheckerContext &C, const CallEvent &Call) const {
1589   // void bcopy(const void *src, void *dst, size_t n);
1590   SourceArgExpr Src{{Call.getArgExpr(0), 0}};
1591   DestinationArgExpr Dest = {{Call.getArgExpr(1), 1}};
1592   SizeArgExpr Size = {{Call.getArgExpr(2), 2}};
1593 
1594   constexpr bool IsRestricted = false;
1595   constexpr bool IsMempcpy = false;
1596   evalCopyCommon(C, Call, C.getState(), Size, Dest, Src, IsRestricted,
1597                  IsMempcpy, CharKind::Regular);
1598 }
1599 
1600 void CStringChecker::evalMemcmp(CheckerContext &C, const CallEvent &Call,
1601                                 CharKind CK) const {
1602   // int memcmp(const void *s1, const void *s2, size_t n);
1603   CurrentFunctionDescription = "memory comparison function";
1604 
1605   AnyArgExpr Left = {Call.getArgExpr(0), 0};
1606   AnyArgExpr Right = {Call.getArgExpr(1), 1};
1607   SizeArgExpr Size = {{Call.getArgExpr(2), 2}};
1608 
1609   ProgramStateRef State = C.getState();
1610   SValBuilder &Builder = C.getSValBuilder();
1611   const LocationContext *LCtx = C.getLocationContext();
1612 
1613   // See if the size argument is zero.
1614   SVal sizeVal = State->getSVal(Size.Expression, LCtx);
1615   QualType sizeTy = Size.Expression->getType();
1616 
1617   ProgramStateRef stateZeroSize, stateNonZeroSize;
1618   std::tie(stateZeroSize, stateNonZeroSize) =
1619       assumeZero(C, State, sizeVal, sizeTy);
1620 
1621   // If the size can be zero, the result will be 0 in that case, and we don't
1622   // have to check either of the buffers.
1623   if (stateZeroSize) {
1624     State = stateZeroSize;
1625     State = State->BindExpr(Call.getOriginExpr(), LCtx,
1626                             Builder.makeZeroVal(Call.getResultType()));
1627     C.addTransition(State);
1628   }
1629 
1630   // If the size can be nonzero, we have to check the other arguments.
1631   if (stateNonZeroSize) {
1632     State = stateNonZeroSize;
1633     // If we know the two buffers are the same, we know the result is 0.
1634     // First, get the two buffers' addresses. Another checker will have already
1635     // made sure they're not undefined.
1636     DefinedOrUnknownSVal LV =
1637         State->getSVal(Left.Expression, LCtx).castAs<DefinedOrUnknownSVal>();
1638     DefinedOrUnknownSVal RV =
1639         State->getSVal(Right.Expression, LCtx).castAs<DefinedOrUnknownSVal>();
1640 
1641     // See if they are the same.
1642     ProgramStateRef SameBuffer, NotSameBuffer;
1643     std::tie(SameBuffer, NotSameBuffer) =
1644         State->assume(Builder.evalEQ(State, LV, RV));
1645 
1646     // If the two arguments are the same buffer, we know the result is 0,
1647     // and we only need to check one size.
1648     if (SameBuffer && !NotSameBuffer) {
1649       State = SameBuffer;
1650       State = CheckBufferAccess(C, State, Left, Size, AccessKind::read);
1651       if (State) {
1652         State = SameBuffer->BindExpr(Call.getOriginExpr(), LCtx,
1653                                      Builder.makeZeroVal(Call.getResultType()));
1654         C.addTransition(State);
1655       }
1656       return;
1657     }
1658 
1659     // If the two arguments might be different buffers, we have to check
1660     // the size of both of them.
1661     assert(NotSameBuffer);
1662     State = CheckBufferAccess(C, State, Right, Size, AccessKind::read, CK);
1663     State = CheckBufferAccess(C, State, Left, Size, AccessKind::read, CK);
1664     if (State) {
1665       // The return value is the comparison result, which we don't know.
1666       SVal CmpV = Builder.conjureSymbolVal(Call, C.blockCount());
1667       State = State->BindExpr(Call.getOriginExpr(), LCtx, CmpV);
1668       C.addTransition(State);
1669     }
1670   }
1671 }
1672 
1673 void CStringChecker::evalstrLength(CheckerContext &C,
1674                                    const CallEvent &Call) const {
1675   // size_t strlen(const char *s);
1676   evalstrLengthCommon(C, Call, /* IsStrnlen = */ false);
1677 }
1678 
1679 void CStringChecker::evalstrnLength(CheckerContext &C,
1680                                     const CallEvent &Call) const {
1681   // size_t strnlen(const char *s, size_t maxlen);
1682   evalstrLengthCommon(C, Call, /* IsStrnlen = */ true);
1683 }
1684 
1685 void CStringChecker::evalstrLengthCommon(CheckerContext &C,
1686                                          const CallEvent &Call,
1687                                          bool IsStrnlen) const {
1688   CurrentFunctionDescription = "string length function";
1689   ProgramStateRef state = C.getState();
1690   const LocationContext *LCtx = C.getLocationContext();
1691 
1692   if (IsStrnlen) {
1693     const Expr *maxlenExpr = Call.getArgExpr(1);
1694     SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
1695 
1696     ProgramStateRef stateZeroSize, stateNonZeroSize;
1697     std::tie(stateZeroSize, stateNonZeroSize) =
1698       assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1699 
1700     // If the size can be zero, the result will be 0 in that case, and we don't
1701     // have to check the string itself.
1702     if (stateZeroSize) {
1703       SVal zero = C.getSValBuilder().makeZeroVal(Call.getResultType());
1704       stateZeroSize = stateZeroSize->BindExpr(Call.getOriginExpr(), LCtx, zero);
1705       C.addTransition(stateZeroSize);
1706     }
1707 
1708     // If the size is GUARANTEED to be zero, we're done!
1709     if (!stateNonZeroSize)
1710       return;
1711 
1712     // Otherwise, record the assumption that the size is nonzero.
1713     state = stateNonZeroSize;
1714   }
1715 
1716   // Check that the string argument is non-null.
1717   AnyArgExpr Arg = {Call.getArgExpr(0), 0};
1718   SVal ArgVal = state->getSVal(Arg.Expression, LCtx);
1719   state = checkNonNull(C, state, Arg, ArgVal);
1720 
1721   if (!state)
1722     return;
1723 
1724   SVal strLength = getCStringLength(C, state, Arg.Expression, ArgVal);
1725 
1726   // If the argument isn't a valid C string, there's no valid state to
1727   // transition to.
1728   if (strLength.isUndef())
1729     return;
1730 
1731   DefinedOrUnknownSVal result = UnknownVal();
1732 
1733   // If the check is for strnlen() then bind the return value to no more than
1734   // the maxlen value.
1735   if (IsStrnlen) {
1736     QualType cmpTy = C.getSValBuilder().getConditionType();
1737 
1738     // It's a little unfortunate to be getting this again,
1739     // but it's not that expensive...
1740     const Expr *maxlenExpr = Call.getArgExpr(1);
1741     SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
1742 
1743     std::optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1744     std::optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
1745 
1746     if (strLengthNL && maxlenValNL) {
1747       ProgramStateRef stateStringTooLong, stateStringNotTooLong;
1748 
1749       // Check if the strLength is greater than the maxlen.
1750       std::tie(stateStringTooLong, stateStringNotTooLong) = state->assume(
1751           C.getSValBuilder()
1752               .evalBinOpNN(state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
1753               .castAs<DefinedOrUnknownSVal>());
1754 
1755       if (stateStringTooLong && !stateStringNotTooLong) {
1756         // If the string is longer than maxlen, return maxlen.
1757         result = *maxlenValNL;
1758       } else if (stateStringNotTooLong && !stateStringTooLong) {
1759         // If the string is shorter than maxlen, return its length.
1760         result = *strLengthNL;
1761       }
1762     }
1763 
1764     if (result.isUnknown()) {
1765       // If we don't have enough information for a comparison, there's
1766       // no guarantee the full string length will actually be returned.
1767       // All we know is the return value is the min of the string length
1768       // and the limit. This is better than nothing.
1769       result = C.getSValBuilder().conjureSymbolVal(Call, C.blockCount());
1770       NonLoc resultNL = result.castAs<NonLoc>();
1771 
1772       if (strLengthNL) {
1773         state = state->assume(C.getSValBuilder().evalBinOpNN(
1774                                   state, BO_LE, resultNL, *strLengthNL, cmpTy)
1775                                   .castAs<DefinedOrUnknownSVal>(), true);
1776       }
1777 
1778       if (maxlenValNL) {
1779         state = state->assume(C.getSValBuilder().evalBinOpNN(
1780                                   state, BO_LE, resultNL, *maxlenValNL, cmpTy)
1781                                   .castAs<DefinedOrUnknownSVal>(), true);
1782       }
1783     }
1784 
1785   } else {
1786     // This is a plain strlen(), not strnlen().
1787     result = strLength.castAs<DefinedOrUnknownSVal>();
1788 
1789     // If we don't know the length of the string, conjure a return
1790     // value, so it can be used in constraints, at least.
1791     if (result.isUnknown()) {
1792       result = C.getSValBuilder().conjureSymbolVal(Call, C.blockCount());
1793     }
1794   }
1795 
1796   // Bind the return value.
1797   assert(!result.isUnknown() && "Should have conjured a value by now");
1798   state = state->BindExpr(Call.getOriginExpr(), LCtx, result);
1799   C.addTransition(state);
1800 }
1801 
1802 void CStringChecker::evalStrcpy(CheckerContext &C,
1803                                 const CallEvent &Call) const {
1804   // char *strcpy(char *restrict dst, const char *restrict src);
1805   evalStrcpyCommon(C, Call,
1806                    /* ReturnEnd = */ false,
1807                    /* IsBounded = */ false,
1808                    /* appendK = */ ConcatFnKind::none);
1809 }
1810 
1811 void CStringChecker::evalStrncpy(CheckerContext &C,
1812                                  const CallEvent &Call) const {
1813   // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
1814   evalStrcpyCommon(C, Call,
1815                    /* ReturnEnd = */ false,
1816                    /* IsBounded = */ true,
1817                    /* appendK = */ ConcatFnKind::none);
1818 }
1819 
1820 void CStringChecker::evalStpcpy(CheckerContext &C,
1821                                 const CallEvent &Call) const {
1822   // char *stpcpy(char *restrict dst, const char *restrict src);
1823   evalStrcpyCommon(C, Call,
1824                    /* ReturnEnd = */ true,
1825                    /* IsBounded = */ false,
1826                    /* appendK = */ ConcatFnKind::none);
1827 }
1828 
1829 void CStringChecker::evalStrlcpy(CheckerContext &C,
1830                                  const CallEvent &Call) const {
1831   // size_t strlcpy(char *dest, const char *src, size_t size);
1832   evalStrcpyCommon(C, Call,
1833                    /* ReturnEnd = */ true,
1834                    /* IsBounded = */ true,
1835                    /* appendK = */ ConcatFnKind::none,
1836                    /* returnPtr = */ false);
1837 }
1838 
1839 void CStringChecker::evalStrcat(CheckerContext &C,
1840                                 const CallEvent &Call) const {
1841   // char *strcat(char *restrict s1, const char *restrict s2);
1842   evalStrcpyCommon(C, Call,
1843                    /* ReturnEnd = */ false,
1844                    /* IsBounded = */ false,
1845                    /* appendK = */ ConcatFnKind::strcat);
1846 }
1847 
1848 void CStringChecker::evalStrncat(CheckerContext &C,
1849                                  const CallEvent &Call) const {
1850   // char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1851   evalStrcpyCommon(C, Call,
1852                    /* ReturnEnd = */ false,
1853                    /* IsBounded = */ true,
1854                    /* appendK = */ ConcatFnKind::strcat);
1855 }
1856 
1857 void CStringChecker::evalStrlcat(CheckerContext &C,
1858                                  const CallEvent &Call) const {
1859   // size_t strlcat(char *dst, const char *src, size_t size);
1860   // It will append at most size - strlen(dst) - 1 bytes,
1861   // NULL-terminating the result.
1862   evalStrcpyCommon(C, Call,
1863                    /* ReturnEnd = */ false,
1864                    /* IsBounded = */ true,
1865                    /* appendK = */ ConcatFnKind::strlcat,
1866                    /* returnPtr = */ false);
1867 }
1868 
1869 void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallEvent &Call,
1870                                       bool ReturnEnd, bool IsBounded,
1871                                       ConcatFnKind appendK,
1872                                       bool returnPtr) const {
1873   if (appendK == ConcatFnKind::none)
1874     CurrentFunctionDescription = "string copy function";
1875   else
1876     CurrentFunctionDescription = "string concatenation function";
1877 
1878   ProgramStateRef state = C.getState();
1879   const LocationContext *LCtx = C.getLocationContext();
1880 
1881   // Check that the destination is non-null.
1882   DestinationArgExpr Dst = {{Call.getArgExpr(0), 0}};
1883   SVal DstVal = state->getSVal(Dst.Expression, LCtx);
1884   state = checkNonNull(C, state, Dst, DstVal);
1885   if (!state)
1886     return;
1887 
1888   // Check that the source is non-null.
1889   SourceArgExpr srcExpr = {{Call.getArgExpr(1), 1}};
1890   SVal srcVal = state->getSVal(srcExpr.Expression, LCtx);
1891   state = checkNonNull(C, state, srcExpr, srcVal);
1892   if (!state)
1893     return;
1894 
1895   // Get the string length of the source.
1896   SVal strLength = getCStringLength(C, state, srcExpr.Expression, srcVal);
1897   std::optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1898 
1899   // Get the string length of the destination buffer.
1900   SVal dstStrLength = getCStringLength(C, state, Dst.Expression, DstVal);
1901   std::optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
1902 
1903   // If the source isn't a valid C string, give up.
1904   if (strLength.isUndef())
1905     return;
1906 
1907   SValBuilder &svalBuilder = C.getSValBuilder();
1908   QualType cmpTy = svalBuilder.getConditionType();
1909   QualType sizeTy = svalBuilder.getContext().getSizeType();
1910 
1911   // These two values allow checking two kinds of errors:
1912   // - actual overflows caused by a source that doesn't fit in the destination
1913   // - potential overflows caused by a bound that could exceed the destination
1914   SVal amountCopied = UnknownVal();
1915   SVal maxLastElementIndex = UnknownVal();
1916   const char *boundWarning = nullptr;
1917 
1918   // FIXME: Why do we choose the srcExpr if the access has no size?
1919   //  Note that the 3rd argument of the call would be the size parameter.
1920   SizeArgExpr SrcExprAsSizeDummy = {
1921       {srcExpr.Expression, srcExpr.ArgumentIndex}};
1922   state = CheckOverlap(
1923       C, state,
1924       (IsBounded ? SizeArgExpr{{Call.getArgExpr(2), 2}} : SrcExprAsSizeDummy),
1925       Dst, srcExpr);
1926 
1927   if (!state)
1928     return;
1929 
1930   // If the function is strncpy, strncat, etc... it is bounded.
1931   if (IsBounded) {
1932     // Get the max number of characters to copy.
1933     SizeArgExpr lenExpr = {{Call.getArgExpr(2), 2}};
1934     SVal lenVal = state->getSVal(lenExpr.Expression, LCtx);
1935 
1936     // Protect against misdeclared strncpy().
1937     lenVal =
1938         svalBuilder.evalCast(lenVal, sizeTy, lenExpr.Expression->getType());
1939 
1940     std::optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
1941 
1942     // If we know both values, we might be able to figure out how much
1943     // we're copying.
1944     if (strLengthNL && lenValNL) {
1945       switch (appendK) {
1946       case ConcatFnKind::none:
1947       case ConcatFnKind::strcat: {
1948         ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
1949         // Check if the max number to copy is less than the length of the src.
1950         // If the bound is equal to the source length, strncpy won't null-
1951         // terminate the result!
1952         std::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
1953             svalBuilder
1954                 .evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
1955                 .castAs<DefinedOrUnknownSVal>());
1956 
1957         if (stateSourceTooLong && !stateSourceNotTooLong) {
1958           // Max number to copy is less than the length of the src, so the
1959           // actual strLength copied is the max number arg.
1960           state = stateSourceTooLong;
1961           amountCopied = lenVal;
1962 
1963         } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1964           // The source buffer entirely fits in the bound.
1965           state = stateSourceNotTooLong;
1966           amountCopied = strLength;
1967         }
1968         break;
1969       }
1970       case ConcatFnKind::strlcat:
1971         if (!dstStrLengthNL)
1972           return;
1973 
1974         // amountCopied = min (size - dstLen - 1 , srcLen)
1975         SVal freeSpace = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1976                                                  *dstStrLengthNL, sizeTy);
1977         if (!isa<NonLoc>(freeSpace))
1978           return;
1979         freeSpace =
1980             svalBuilder.evalBinOp(state, BO_Sub, freeSpace,
1981                                   svalBuilder.makeIntVal(1, sizeTy), sizeTy);
1982         std::optional<NonLoc> freeSpaceNL = freeSpace.getAs<NonLoc>();
1983 
1984         // While unlikely, it is possible that the subtraction is
1985         // too complex to compute, let's check whether it succeeded.
1986         if (!freeSpaceNL)
1987           return;
1988         SVal hasEnoughSpace = svalBuilder.evalBinOpNN(
1989             state, BO_LE, *strLengthNL, *freeSpaceNL, cmpTy);
1990 
1991         ProgramStateRef TrueState, FalseState;
1992         std::tie(TrueState, FalseState) =
1993             state->assume(hasEnoughSpace.castAs<DefinedOrUnknownSVal>());
1994 
1995         // srcStrLength <= size - dstStrLength -1
1996         if (TrueState && !FalseState) {
1997           amountCopied = strLength;
1998         }
1999 
2000         // srcStrLength > size - dstStrLength -1
2001         if (!TrueState && FalseState) {
2002           amountCopied = freeSpace;
2003         }
2004 
2005         if (TrueState && FalseState)
2006           amountCopied = UnknownVal();
2007         break;
2008       }
2009     }
2010     // We still want to know if the bound is known to be too large.
2011     if (lenValNL) {
2012       switch (appendK) {
2013       case ConcatFnKind::strcat:
2014         // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
2015 
2016         // Get the string length of the destination. If the destination is
2017         // memory that can't have a string length, we shouldn't be copying
2018         // into it anyway.
2019         if (dstStrLength.isUndef())
2020           return;
2021 
2022         if (dstStrLengthNL) {
2023           maxLastElementIndex = svalBuilder.evalBinOpNN(
2024               state, BO_Add, *lenValNL, *dstStrLengthNL, sizeTy);
2025 
2026           boundWarning = "Size argument is greater than the free space in the "
2027                          "destination buffer";
2028         }
2029         break;
2030       case ConcatFnKind::none:
2031       case ConcatFnKind::strlcat:
2032         // For strncpy and strlcat, this is just checking
2033         //  that lenVal <= sizeof(dst).
2034         // (Yes, strncpy and strncat differ in how they treat termination.
2035         // strncat ALWAYS terminates, but strncpy doesn't.)
2036 
2037         // We need a special case for when the copy size is zero, in which
2038         // case strncpy will do no work at all. Our bounds check uses n-1
2039         // as the last element accessed, so n == 0 is problematic.
2040         ProgramStateRef StateZeroSize, StateNonZeroSize;
2041         std::tie(StateZeroSize, StateNonZeroSize) =
2042             assumeZero(C, state, *lenValNL, sizeTy);
2043 
2044         // If the size is known to be zero, we're done.
2045         if (StateZeroSize && !StateNonZeroSize) {
2046           if (returnPtr) {
2047             StateZeroSize =
2048                 StateZeroSize->BindExpr(Call.getOriginExpr(), LCtx, DstVal);
2049           } else {
2050             if (appendK == ConcatFnKind::none) {
2051               // strlcpy returns strlen(src)
2052               StateZeroSize = StateZeroSize->BindExpr(Call.getOriginExpr(),
2053                                                       LCtx, strLength);
2054             } else {
2055               // strlcat returns strlen(src) + strlen(dst)
2056               SVal retSize = svalBuilder.evalBinOp(
2057                   state, BO_Add, strLength, dstStrLength, sizeTy);
2058               StateZeroSize =
2059                   StateZeroSize->BindExpr(Call.getOriginExpr(), LCtx, retSize);
2060             }
2061           }
2062           C.addTransition(StateZeroSize);
2063           return;
2064         }
2065 
2066         // Otherwise, go ahead and figure out the last element we'll touch.
2067         // We don't record the non-zero assumption here because we can't
2068         // be sure. We won't warn on a possible zero.
2069         NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
2070         maxLastElementIndex =
2071             svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL, one, sizeTy);
2072         boundWarning = "Size argument is greater than the length of the "
2073                        "destination buffer";
2074         break;
2075       }
2076     }
2077   } else {
2078     // The function isn't bounded. The amount copied should match the length
2079     // of the source buffer.
2080     amountCopied = strLength;
2081   }
2082 
2083   assert(state);
2084 
2085   // This represents the number of characters copied into the destination
2086   // buffer. (It may not actually be the strlen if the destination buffer
2087   // is not terminated.)
2088   SVal finalStrLength = UnknownVal();
2089   SVal strlRetVal = UnknownVal();
2090 
2091   if (appendK == ConcatFnKind::none && !returnPtr) {
2092     // strlcpy returns the sizeof(src)
2093     strlRetVal = strLength;
2094   }
2095 
2096   // If this is an appending function (strcat, strncat...) then set the
2097   // string length to strlen(src) + strlen(dst) since the buffer will
2098   // ultimately contain both.
2099   if (appendK != ConcatFnKind::none) {
2100     // Get the string length of the destination. If the destination is memory
2101     // that can't have a string length, we shouldn't be copying into it anyway.
2102     if (dstStrLength.isUndef())
2103       return;
2104 
2105     if (appendK == ConcatFnKind::strlcat && dstStrLengthNL && strLengthNL) {
2106       strlRetVal = svalBuilder.evalBinOpNN(state, BO_Add, *strLengthNL,
2107                                            *dstStrLengthNL, sizeTy);
2108     }
2109 
2110     std::optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>();
2111 
2112     // If we know both string lengths, we might know the final string length.
2113     if (amountCopiedNL && dstStrLengthNL) {
2114       // Make sure the two lengths together don't overflow a size_t.
2115       state = checkAdditionOverflow(C, state, *amountCopiedNL, *dstStrLengthNL);
2116       if (!state)
2117         return;
2118 
2119       finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *amountCopiedNL,
2120                                                *dstStrLengthNL, sizeTy);
2121     }
2122 
2123     // If we couldn't get a single value for the final string length,
2124     // we can at least bound it by the individual lengths.
2125     if (finalStrLength.isUnknown()) {
2126       // Try to get a "hypothetical" string length symbol, which we can later
2127       // set as a real value if that turns out to be the case.
2128       finalStrLength =
2129           getCStringLength(C, state, Call.getOriginExpr(), DstVal, true);
2130       assert(!finalStrLength.isUndef());
2131 
2132       if (std::optional<NonLoc> finalStrLengthNL =
2133               finalStrLength.getAs<NonLoc>()) {
2134         if (amountCopiedNL && appendK == ConcatFnKind::none) {
2135           // we overwrite dst string with the src
2136           // finalStrLength >= srcStrLength
2137           SVal sourceInResult = svalBuilder.evalBinOpNN(
2138               state, BO_GE, *finalStrLengthNL, *amountCopiedNL, cmpTy);
2139           state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
2140                                 true);
2141           if (!state)
2142             return;
2143         }
2144 
2145         if (dstStrLengthNL && appendK != ConcatFnKind::none) {
2146           // we extend the dst string with the src
2147           // finalStrLength >= dstStrLength
2148           SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
2149                                                       *finalStrLengthNL,
2150                                                       *dstStrLengthNL,
2151                                                       cmpTy);
2152           state =
2153               state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
2154           if (!state)
2155             return;
2156         }
2157       }
2158     }
2159 
2160   } else {
2161     // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
2162     // the final string length will match the input string length.
2163     finalStrLength = amountCopied;
2164   }
2165 
2166   SVal Result;
2167 
2168   if (returnPtr) {
2169     // The final result of the function will either be a pointer past the last
2170     // copied element, or a pointer to the start of the destination buffer.
2171     Result = (ReturnEnd ? UnknownVal() : DstVal);
2172   } else {
2173     if (appendK == ConcatFnKind::strlcat || appendK == ConcatFnKind::none)
2174       //strlcpy, strlcat
2175       Result = strlRetVal;
2176     else
2177       Result = finalStrLength;
2178   }
2179 
2180   assert(state);
2181 
2182   // If the destination is a MemRegion, try to check for a buffer overflow and
2183   // record the new string length.
2184   if (std::optional<loc::MemRegionVal> dstRegVal =
2185           DstVal.getAs<loc::MemRegionVal>()) {
2186     QualType ptrTy = Dst.Expression->getType();
2187 
2188     // If we have an exact value on a bounded copy, use that to check for
2189     // overflows, rather than our estimate about how much is actually copied.
2190     if (std::optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
2191       SVal maxLastElement =
2192           svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal, *maxLastNL, ptrTy);
2193 
2194       // Check if the first byte of the destination is writable.
2195       state = CheckLocation(C, state, Dst, DstVal, AccessKind::write);
2196       if (!state)
2197         return;
2198       // Check if the last byte of the destination is writable.
2199       state = CheckLocation(C, state, Dst, maxLastElement, AccessKind::write);
2200       if (!state)
2201         return;
2202     }
2203 
2204     // Then, if the final length is known...
2205     if (std::optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
2206       SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
2207           *knownStrLength, ptrTy);
2208 
2209       // ...and we haven't checked the bound, we'll check the actual copy.
2210       if (!boundWarning) {
2211         // Check if the first byte of the destination is writable.
2212         state = CheckLocation(C, state, Dst, DstVal, AccessKind::write);
2213         if (!state)
2214           return;
2215         // Check if the last byte of the destination is writable.
2216         state = CheckLocation(C, state, Dst, lastElement, AccessKind::write);
2217         if (!state)
2218           return;
2219       }
2220 
2221       // If this is a stpcpy-style copy, the last element is the return value.
2222       if (returnPtr && ReturnEnd)
2223         Result = lastElement;
2224     }
2225 
2226     // For bounded method, amountCopied take the minimum of two values,
2227     // for ConcatFnKind::strlcat:
2228     // amountCopied = min (size - dstLen - 1 , srcLen)
2229     // for others:
2230     // amountCopied = min (srcLen, size)
2231     // So even if we don't know about amountCopied, as long as one of them will
2232     // not cause an out-of-bound access, the whole function's operation will not
2233     // too, that will avoid invalidating the superRegion of data member in that
2234     // situation.
2235     bool CouldAccessOutOfBound = true;
2236     if (IsBounded && amountCopied.isUnknown()) {
2237       auto CouldAccessOutOfBoundForSVal =
2238           [&](std::optional<NonLoc> Val) -> bool {
2239         if (!Val)
2240           return true;
2241         return !isFirstBufInBound(C, state, C.getSVal(Dst.Expression),
2242                                   Dst.Expression->getType(), *Val,
2243                                   C.getASTContext().getSizeType());
2244       };
2245 
2246       CouldAccessOutOfBound = CouldAccessOutOfBoundForSVal(strLengthNL);
2247 
2248       if (CouldAccessOutOfBound) {
2249         // Get the max number of characters to copy.
2250         const Expr *LenExpr = Call.getArgExpr(2);
2251         SVal LenVal = state->getSVal(LenExpr, LCtx);
2252 
2253         // Protect against misdeclared strncpy().
2254         LenVal = svalBuilder.evalCast(LenVal, sizeTy, LenExpr->getType());
2255 
2256         // Because analyzer doesn't handle expressions like `size -
2257         // dstLen - 1` very well, we roughly use `size` for
2258         // ConcatFnKind::strlcat here, same with other concat kinds.
2259         CouldAccessOutOfBound =
2260             CouldAccessOutOfBoundForSVal(LenVal.getAs<NonLoc>());
2261       }
2262     }
2263 
2264     // Invalidate the destination (regular invalidation without pointer-escaping
2265     // the address of the top-level region). This must happen before we set the
2266     // C string length because invalidation will clear the length.
2267     // FIXME: Even if we can't perfectly model the copy, we should see if we
2268     // can use LazyCompoundVals to copy the source values into the destination.
2269     // This would probably remove any existing bindings past the end of the
2270     // string, but that's still an improvement over blank invalidation.
2271     if (CouldAccessOutOfBound)
2272       state = invalidateDestinationBufferBySize(
2273           C, state, Dst.Expression, Call.getCFGElementRef(), *dstRegVal,
2274           amountCopied, C.getASTContext().getSizeType());
2275     else
2276       state = invalidateDestinationBufferNeverOverflows(
2277           C, state, Call.getCFGElementRef(), *dstRegVal);
2278 
2279     // Invalidate the source (const-invalidation without const-pointer-escaping
2280     // the address of the top-level region).
2281     state = invalidateSourceBuffer(C, state, Call.getCFGElementRef(), srcVal);
2282 
2283     // Set the C string length of the destination, if we know it.
2284     if (IsBounded && (appendK == ConcatFnKind::none)) {
2285       // strncpy is annoying in that it doesn't guarantee to null-terminate
2286       // the result string. If the original string didn't fit entirely inside
2287       // the bound (including the null-terminator), we don't know how long the
2288       // result is.
2289       if (amountCopied != strLength)
2290         finalStrLength = UnknownVal();
2291     }
2292     state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
2293   }
2294 
2295   assert(state);
2296 
2297   if (returnPtr) {
2298     // If this is a stpcpy-style copy, but we were unable to check for a buffer
2299     // overflow, we still need a result. Conjure a return value.
2300     if (ReturnEnd && Result.isUnknown()) {
2301       Result = svalBuilder.conjureSymbolVal(Call, C.blockCount());
2302     }
2303   }
2304   // Set the return value.
2305   state = state->BindExpr(Call.getOriginExpr(), LCtx, Result);
2306   C.addTransition(state);
2307 }
2308 
2309 void CStringChecker::evalStrcmp(CheckerContext &C,
2310                                 const CallEvent &Call) const {
2311   //int strcmp(const char *s1, const char *s2);
2312   evalStrcmpCommon(C, Call, /* IsBounded = */ false, /* IgnoreCase = */ false);
2313 }
2314 
2315 void CStringChecker::evalStrncmp(CheckerContext &C,
2316                                  const CallEvent &Call) const {
2317   //int strncmp(const char *s1, const char *s2, size_t n);
2318   evalStrcmpCommon(C, Call, /* IsBounded = */ true, /* IgnoreCase = */ false);
2319 }
2320 
2321 void CStringChecker::evalStrcasecmp(CheckerContext &C,
2322                                     const CallEvent &Call) const {
2323   //int strcasecmp(const char *s1, const char *s2);
2324   evalStrcmpCommon(C, Call, /* IsBounded = */ false, /* IgnoreCase = */ true);
2325 }
2326 
2327 void CStringChecker::evalStrncasecmp(CheckerContext &C,
2328                                      const CallEvent &Call) const {
2329   //int strncasecmp(const char *s1, const char *s2, size_t n);
2330   evalStrcmpCommon(C, Call, /* IsBounded = */ true, /* IgnoreCase = */ true);
2331 }
2332 
2333 void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallEvent &Call,
2334                                       bool IsBounded, bool IgnoreCase) const {
2335   CurrentFunctionDescription = "string comparison function";
2336   ProgramStateRef state = C.getState();
2337   const LocationContext *LCtx = C.getLocationContext();
2338 
2339   // Check that the first string is non-null
2340   AnyArgExpr Left = {Call.getArgExpr(0), 0};
2341   SVal LeftVal = state->getSVal(Left.Expression, LCtx);
2342   state = checkNonNull(C, state, Left, LeftVal);
2343   if (!state)
2344     return;
2345 
2346   // Check that the second string is non-null.
2347   AnyArgExpr Right = {Call.getArgExpr(1), 1};
2348   SVal RightVal = state->getSVal(Right.Expression, LCtx);
2349   state = checkNonNull(C, state, Right, RightVal);
2350   if (!state)
2351     return;
2352 
2353   // Get the string length of the first string or give up.
2354   SVal LeftLength = getCStringLength(C, state, Left.Expression, LeftVal);
2355   if (LeftLength.isUndef())
2356     return;
2357 
2358   // Get the string length of the second string or give up.
2359   SVal RightLength = getCStringLength(C, state, Right.Expression, RightVal);
2360   if (RightLength.isUndef())
2361     return;
2362 
2363   // If we know the two buffers are the same, we know the result is 0.
2364   // First, get the two buffers' addresses. Another checker will have already
2365   // made sure they're not undefined.
2366   DefinedOrUnknownSVal LV = LeftVal.castAs<DefinedOrUnknownSVal>();
2367   DefinedOrUnknownSVal RV = RightVal.castAs<DefinedOrUnknownSVal>();
2368 
2369   // See if they are the same.
2370   SValBuilder &svalBuilder = C.getSValBuilder();
2371   DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
2372   ProgramStateRef StSameBuf, StNotSameBuf;
2373   std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
2374 
2375   // If the two arguments might be the same buffer, we know the result is 0,
2376   // and we only need to check one size.
2377   if (StSameBuf) {
2378     StSameBuf =
2379         StSameBuf->BindExpr(Call.getOriginExpr(), LCtx,
2380                             svalBuilder.makeZeroVal(Call.getResultType()));
2381     C.addTransition(StSameBuf);
2382 
2383     // If the two arguments are GUARANTEED to be the same, we're done!
2384     if (!StNotSameBuf)
2385       return;
2386   }
2387 
2388   assert(StNotSameBuf);
2389   state = StNotSameBuf;
2390 
2391   // At this point we can go about comparing the two buffers.
2392   // For now, we only do this if they're both known string literals.
2393 
2394   // Attempt to extract string literals from both expressions.
2395   const StringLiteral *LeftStrLiteral =
2396       getCStringLiteral(C, state, Left.Expression, LeftVal);
2397   const StringLiteral *RightStrLiteral =
2398       getCStringLiteral(C, state, Right.Expression, RightVal);
2399   bool canComputeResult = false;
2400   SVal resultVal = svalBuilder.conjureSymbolVal(Call, C.blockCount());
2401 
2402   if (LeftStrLiteral && RightStrLiteral) {
2403     StringRef LeftStrRef = LeftStrLiteral->getString();
2404     StringRef RightStrRef = RightStrLiteral->getString();
2405 
2406     if (IsBounded) {
2407       // Get the max number of characters to compare.
2408       const Expr *lenExpr = Call.getArgExpr(2);
2409       SVal lenVal = state->getSVal(lenExpr, LCtx);
2410 
2411       // If the length is known, we can get the right substrings.
2412       if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
2413         // Create substrings of each to compare the prefix.
2414         LeftStrRef = LeftStrRef.substr(0, (size_t)len->getZExtValue());
2415         RightStrRef = RightStrRef.substr(0, (size_t)len->getZExtValue());
2416         canComputeResult = true;
2417       }
2418     } else {
2419       // This is a normal, unbounded strcmp.
2420       canComputeResult = true;
2421     }
2422 
2423     if (canComputeResult) {
2424       // Real strcmp stops at null characters.
2425       size_t s1Term = LeftStrRef.find('\0');
2426       if (s1Term != StringRef::npos)
2427         LeftStrRef = LeftStrRef.substr(0, s1Term);
2428 
2429       size_t s2Term = RightStrRef.find('\0');
2430       if (s2Term != StringRef::npos)
2431         RightStrRef = RightStrRef.substr(0, s2Term);
2432 
2433       // Use StringRef's comparison methods to compute the actual result.
2434       int compareRes = IgnoreCase ? LeftStrRef.compare_insensitive(RightStrRef)
2435                                   : LeftStrRef.compare(RightStrRef);
2436 
2437       // The strcmp function returns an integer greater than, equal to, or less
2438       // than zero, [c11, p7.24.4.2].
2439       if (compareRes == 0) {
2440         resultVal = svalBuilder.makeIntVal(compareRes, Call.getResultType());
2441       }
2442       else {
2443         DefinedSVal zeroVal = svalBuilder.makeIntVal(0, Call.getResultType());
2444         // Constrain strcmp's result range based on the result of StringRef's
2445         // comparison methods.
2446         BinaryOperatorKind op = (compareRes > 0) ? BO_GT : BO_LT;
2447         SVal compareWithZero =
2448           svalBuilder.evalBinOp(state, op, resultVal, zeroVal,
2449               svalBuilder.getConditionType());
2450         DefinedSVal compareWithZeroVal = compareWithZero.castAs<DefinedSVal>();
2451         state = state->assume(compareWithZeroVal, true);
2452       }
2453     }
2454   }
2455 
2456   state = state->BindExpr(Call.getOriginExpr(), LCtx, resultVal);
2457 
2458   // Record this as a possible path.
2459   C.addTransition(state);
2460 }
2461 
2462 void CStringChecker::evalStrsep(CheckerContext &C,
2463                                 const CallEvent &Call) const {
2464   // char *strsep(char **stringp, const char *delim);
2465   // Verify whether the search string parameter matches the return type.
2466   SourceArgExpr SearchStrPtr = {{Call.getArgExpr(0), 0}};
2467 
2468   QualType CharPtrTy = SearchStrPtr.Expression->getType()->getPointeeType();
2469   if (CharPtrTy.isNull() || Call.getResultType().getUnqualifiedType() !=
2470                                 CharPtrTy.getUnqualifiedType())
2471     return;
2472 
2473   CurrentFunctionDescription = "strsep()";
2474   ProgramStateRef State = C.getState();
2475   const LocationContext *LCtx = C.getLocationContext();
2476 
2477   // Check that the search string pointer is non-null (though it may point to
2478   // a null string).
2479   SVal SearchStrVal = State->getSVal(SearchStrPtr.Expression, LCtx);
2480   State = checkNonNull(C, State, SearchStrPtr, SearchStrVal);
2481   if (!State)
2482     return;
2483 
2484   // Check that the delimiter string is non-null.
2485   AnyArgExpr DelimStr = {Call.getArgExpr(1), 1};
2486   SVal DelimStrVal = State->getSVal(DelimStr.Expression, LCtx);
2487   State = checkNonNull(C, State, DelimStr, DelimStrVal);
2488   if (!State)
2489     return;
2490 
2491   SValBuilder &SVB = C.getSValBuilder();
2492   SVal Result;
2493   if (std::optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
2494     // Get the current value of the search string pointer, as a char*.
2495     Result = State->getSVal(*SearchStrLoc, CharPtrTy);
2496 
2497     // Invalidate the search string, representing the change of one delimiter
2498     // character to NUL.
2499     // As the replacement never overflows, do not invalidate its super region.
2500     State = invalidateDestinationBufferNeverOverflows(
2501         C, State, Call.getCFGElementRef(), Result);
2502 
2503     // Overwrite the search string pointer. The new value is either an address
2504     // further along in the same string, or NULL if there are no more tokens.
2505     State = State->bindLoc(*SearchStrLoc,
2506                            SVB.conjureSymbolVal(Call, C.blockCount(), getTag()),
2507                            LCtx);
2508   } else {
2509     assert(SearchStrVal.isUnknown());
2510     // Conjure a symbolic value. It's the best we can do.
2511     Result = SVB.conjureSymbolVal(Call, C.blockCount());
2512   }
2513 
2514   // Set the return value, and finish.
2515   State = State->BindExpr(Call.getOriginExpr(), LCtx, Result);
2516   C.addTransition(State);
2517 }
2518 
2519 // These should probably be moved into a C++ standard library checker.
2520 void CStringChecker::evalStdCopy(CheckerContext &C,
2521                                  const CallEvent &Call) const {
2522   evalStdCopyCommon(C, Call);
2523 }
2524 
2525 void CStringChecker::evalStdCopyBackward(CheckerContext &C,
2526                                          const CallEvent &Call) const {
2527   evalStdCopyCommon(C, Call);
2528 }
2529 
2530 void CStringChecker::evalStdCopyCommon(CheckerContext &C,
2531                                        const CallEvent &Call) const {
2532   if (!Call.getArgExpr(2)->getType()->isPointerType())
2533     return;
2534 
2535   ProgramStateRef State = C.getState();
2536 
2537   const LocationContext *LCtx = C.getLocationContext();
2538 
2539   // template <class _InputIterator, class _OutputIterator>
2540   // _OutputIterator
2541   // copy(_InputIterator __first, _InputIterator __last,
2542   //        _OutputIterator __result)
2543 
2544   // Invalidate the destination buffer
2545   const Expr *Dst = Call.getArgExpr(2);
2546   SVal DstVal = State->getSVal(Dst, LCtx);
2547   // FIXME: As we do not know how many items are copied, we also invalidate the
2548   // super region containing the target location.
2549   State = invalidateDestinationBufferAlwaysEscapeSuperRegion(
2550       C, State, Call.getCFGElementRef(), DstVal);
2551 
2552   SValBuilder &SVB = C.getSValBuilder();
2553 
2554   SVal ResultVal = SVB.conjureSymbolVal(Call, C.blockCount());
2555   State = State->BindExpr(Call.getOriginExpr(), LCtx, ResultVal);
2556 
2557   C.addTransition(State);
2558 }
2559 
2560 void CStringChecker::evalMemset(CheckerContext &C,
2561                                 const CallEvent &Call) const {
2562   // void *memset(void *s, int c, size_t n);
2563   CurrentFunctionDescription = "memory set function";
2564 
2565   DestinationArgExpr Buffer = {{Call.getArgExpr(0), 0}};
2566   AnyArgExpr CharE = {Call.getArgExpr(1), 1};
2567   SizeArgExpr Size = {{Call.getArgExpr(2), 2}};
2568 
2569   ProgramStateRef State = C.getState();
2570 
2571   // See if the size argument is zero.
2572   const LocationContext *LCtx = C.getLocationContext();
2573   SVal SizeVal = C.getSVal(Size.Expression);
2574   QualType SizeTy = Size.Expression->getType();
2575 
2576   ProgramStateRef ZeroSize, NonZeroSize;
2577   std::tie(ZeroSize, NonZeroSize) = assumeZero(C, State, SizeVal, SizeTy);
2578 
2579   // Get the value of the memory area.
2580   SVal BufferPtrVal = C.getSVal(Buffer.Expression);
2581 
2582   // If the size is zero, there won't be any actual memory access, so
2583   // just bind the return value to the buffer and return.
2584   if (ZeroSize && !NonZeroSize) {
2585     ZeroSize = ZeroSize->BindExpr(Call.getOriginExpr(), LCtx, BufferPtrVal);
2586     C.addTransition(ZeroSize);
2587     return;
2588   }
2589 
2590   // Ensure the memory area is not null.
2591   // If it is NULL there will be a NULL pointer dereference.
2592   State = checkNonNull(C, NonZeroSize, Buffer, BufferPtrVal);
2593   if (!State)
2594     return;
2595 
2596   State = CheckBufferAccess(C, State, Buffer, Size, AccessKind::write);
2597   if (!State)
2598     return;
2599 
2600   // According to the values of the arguments, bind the value of the second
2601   // argument to the destination buffer and set string length, or just
2602   // invalidate the destination buffer.
2603   if (!memsetAux(Buffer.Expression, Call.getCFGElementRef(),
2604                  C.getSVal(CharE.Expression), Size.Expression, C, State))
2605     return;
2606 
2607   State = State->BindExpr(Call.getOriginExpr(), LCtx, BufferPtrVal);
2608   C.addTransition(State);
2609 }
2610 
2611 void CStringChecker::evalBzero(CheckerContext &C, const CallEvent &Call) const {
2612   CurrentFunctionDescription = "memory clearance function";
2613 
2614   DestinationArgExpr Buffer = {{Call.getArgExpr(0), 0}};
2615   SizeArgExpr Size = {{Call.getArgExpr(1), 1}};
2616   SVal Zero = C.getSValBuilder().makeZeroVal(C.getASTContext().IntTy);
2617 
2618   ProgramStateRef State = C.getState();
2619 
2620   // See if the size argument is zero.
2621   SVal SizeVal = C.getSVal(Size.Expression);
2622   QualType SizeTy = Size.Expression->getType();
2623 
2624   ProgramStateRef StateZeroSize, StateNonZeroSize;
2625   std::tie(StateZeroSize, StateNonZeroSize) =
2626     assumeZero(C, State, SizeVal, SizeTy);
2627 
2628   // If the size is zero, there won't be any actual memory access,
2629   // In this case we just return.
2630   if (StateZeroSize && !StateNonZeroSize) {
2631     C.addTransition(StateZeroSize);
2632     return;
2633   }
2634 
2635   // Get the value of the memory area.
2636   SVal MemVal = C.getSVal(Buffer.Expression);
2637 
2638   // Ensure the memory area is not null.
2639   // If it is NULL there will be a NULL pointer dereference.
2640   State = checkNonNull(C, StateNonZeroSize, Buffer, MemVal);
2641   if (!State)
2642     return;
2643 
2644   State = CheckBufferAccess(C, State, Buffer, Size, AccessKind::write);
2645   if (!State)
2646     return;
2647 
2648   if (!memsetAux(Buffer.Expression, Call.getCFGElementRef(), Zero,
2649                  Size.Expression, C, State))
2650     return;
2651 
2652   C.addTransition(State);
2653 }
2654 
2655 void CStringChecker::evalSprintf(CheckerContext &C,
2656                                  const CallEvent &Call) const {
2657   CurrentFunctionDescription = "'sprintf'";
2658   evalSprintfCommon(C, Call, /* IsBounded = */ false);
2659 }
2660 
2661 void CStringChecker::evalSnprintf(CheckerContext &C,
2662                                   const CallEvent &Call) const {
2663   CurrentFunctionDescription = "'snprintf'";
2664   evalSprintfCommon(C, Call, /* IsBounded = */ true);
2665 }
2666 
2667 void CStringChecker::evalSprintfCommon(CheckerContext &C, const CallEvent &Call,
2668                                        bool IsBounded) const {
2669   ProgramStateRef State = C.getState();
2670   const auto *CE = cast<CallExpr>(Call.getOriginExpr());
2671   DestinationArgExpr Dest = {{Call.getArgExpr(0), 0}};
2672 
2673   const auto NumParams = Call.parameters().size();
2674   if (CE->getNumArgs() < NumParams) {
2675     // This is an invalid call, let's just ignore it.
2676     return;
2677   }
2678 
2679   const auto AllArguments =
2680       llvm::make_range(CE->getArgs(), CE->getArgs() + CE->getNumArgs());
2681   const auto VariadicArguments = drop_begin(enumerate(AllArguments), NumParams);
2682 
2683   for (const auto &[ArgIdx, ArgExpr] : VariadicArguments) {
2684     // We consider only string buffers
2685     if (const QualType type = ArgExpr->getType();
2686         !type->isAnyPointerType() ||
2687         !type->getPointeeType()->isAnyCharacterType())
2688       continue;
2689     SourceArgExpr Source = {{ArgExpr, unsigned(ArgIdx)}};
2690 
2691     // Ensure the buffers do not overlap.
2692     SizeArgExpr SrcExprAsSizeDummy = {
2693         {Source.Expression, Source.ArgumentIndex}};
2694     State = CheckOverlap(
2695         C, State,
2696         (IsBounded ? SizeArgExpr{{Call.getArgExpr(1), 1}} : SrcExprAsSizeDummy),
2697         Dest, Source);
2698     if (!State)
2699       return;
2700   }
2701 
2702   C.addTransition(State);
2703 }
2704 
2705 //===----------------------------------------------------------------------===//
2706 // The driver method, and other Checker callbacks.
2707 //===----------------------------------------------------------------------===//
2708 
2709 CStringChecker::FnCheck CStringChecker::identifyCall(const CallEvent &Call,
2710                                                      CheckerContext &C) const {
2711   const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
2712   if (!CE)
2713     return nullptr;
2714 
2715   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
2716   if (!FD)
2717     return nullptr;
2718 
2719   if (StdCopy.matches(Call))
2720     return &CStringChecker::evalStdCopy;
2721   if (StdCopyBackward.matches(Call))
2722     return &CStringChecker::evalStdCopyBackward;
2723 
2724   // Pro-actively check that argument types are safe to do arithmetic upon.
2725   // We do not want to crash if someone accidentally passes a structure
2726   // into, say, a C++ overload of any of these functions. We could not check
2727   // that for std::copy because they may have arguments of other types.
2728   for (auto I : CE->arguments()) {
2729     QualType T = I->getType();
2730     if (!T->isIntegralOrEnumerationType() && !T->isPointerType())
2731       return nullptr;
2732   }
2733 
2734   const FnCheck *Callback = Callbacks.lookup(Call);
2735   if (Callback)
2736     return *Callback;
2737 
2738   return nullptr;
2739 }
2740 
2741 bool CStringChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
2742   FnCheck Callback = identifyCall(Call, C);
2743 
2744   // If the callee isn't a string function, let another checker handle it.
2745   if (!Callback)
2746     return false;
2747 
2748   // Check and evaluate the call.
2749   assert(isa<CallExpr>(Call.getOriginExpr()));
2750   Callback(this, C, Call);
2751 
2752   // If the evaluate call resulted in no change, chain to the next eval call
2753   // handler.
2754   // Note, the custom CString evaluation calls assume that basic safety
2755   // properties are held. However, if the user chooses to turn off some of these
2756   // checks, we ignore the issues and leave the call evaluation to a generic
2757   // handler.
2758   return C.isDifferent();
2759 }
2760 
2761 void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
2762   // Record string length for char a[] = "abc";
2763   ProgramStateRef state = C.getState();
2764 
2765   for (const auto *I : DS->decls()) {
2766     const VarDecl *D = dyn_cast<VarDecl>(I);
2767     if (!D)
2768       continue;
2769 
2770     // FIXME: Handle array fields of structs.
2771     if (!D->getType()->isArrayType())
2772       continue;
2773 
2774     const Expr *Init = D->getInit();
2775     if (!Init)
2776       continue;
2777     if (!isa<StringLiteral>(Init))
2778       continue;
2779 
2780     Loc VarLoc = state->getLValue(D, C.getLocationContext());
2781     const MemRegion *MR = VarLoc.getAsRegion();
2782     if (!MR)
2783       continue;
2784 
2785     SVal StrVal = C.getSVal(Init);
2786     assert(StrVal.isValid() && "Initializer string is unknown or undefined");
2787     DefinedOrUnknownSVal strLength =
2788       getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
2789 
2790     state = state->set<CStringLength>(MR, strLength);
2791   }
2792 
2793   C.addTransition(state);
2794 }
2795 
2796 ProgramStateRef
2797 CStringChecker::checkRegionChanges(ProgramStateRef state,
2798     const InvalidatedSymbols *,
2799     ArrayRef<const MemRegion *> ExplicitRegions,
2800     ArrayRef<const MemRegion *> Regions,
2801     const LocationContext *LCtx,
2802     const CallEvent *Call) const {
2803   CStringLengthTy Entries = state->get<CStringLength>();
2804   if (Entries.isEmpty())
2805     return state;
2806 
2807   llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
2808   llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
2809 
2810   // First build sets for the changed regions and their super-regions.
2811   for (const MemRegion *MR : Regions) {
2812     Invalidated.insert(MR);
2813 
2814     SuperRegions.insert(MR);
2815     while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
2816       MR = SR->getSuperRegion();
2817       SuperRegions.insert(MR);
2818     }
2819   }
2820 
2821   CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2822 
2823   // Then loop over the entries in the current state.
2824   for (const MemRegion *MR : llvm::make_first_range(Entries)) {
2825     // Is this entry for a super-region of a changed region?
2826     if (SuperRegions.count(MR)) {
2827       Entries = F.remove(Entries, MR);
2828       continue;
2829     }
2830 
2831     // Is this entry for a sub-region of a changed region?
2832     const MemRegion *Super = MR;
2833     while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
2834       Super = SR->getSuperRegion();
2835       if (Invalidated.count(Super)) {
2836         Entries = F.remove(Entries, MR);
2837         break;
2838       }
2839     }
2840   }
2841 
2842   return state->set<CStringLength>(Entries);
2843 }
2844 
2845 void CStringChecker::checkLiveSymbols(ProgramStateRef state,
2846     SymbolReaper &SR) const {
2847   // Mark all symbols in our string length map as valid.
2848   CStringLengthTy Entries = state->get<CStringLength>();
2849 
2850   for (SVal Len : llvm::make_second_range(Entries)) {
2851     for (SymbolRef Sym : Len.symbols())
2852       SR.markInUse(Sym);
2853   }
2854 }
2855 
2856 void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
2857     CheckerContext &C) const {
2858   ProgramStateRef state = C.getState();
2859   CStringLengthTy Entries = state->get<CStringLength>();
2860   if (Entries.isEmpty())
2861     return;
2862 
2863   CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2864   for (auto [Reg, Len] : Entries) {
2865     if (SymbolRef Sym = Len.getAsSymbol()) {
2866       if (SR.isDead(Sym))
2867         Entries = F.remove(Entries, Reg);
2868     }
2869   }
2870 
2871   state = state->set<CStringLength>(Entries);
2872   C.addTransition(state);
2873 }
2874 
2875 void ento::registerCStringModeling(CheckerManager &Mgr) {
2876   Mgr.registerChecker<CStringChecker>();
2877 }
2878 
2879 bool ento::shouldRegisterCStringModeling(const CheckerManager &mgr) {
2880   return true;
2881 }
2882 
2883 #define REGISTER_CHECKER(name)                                                 \
2884   void ento::register##name(CheckerManager &mgr) {                             \
2885     CStringChecker *checker = mgr.getChecker<CStringChecker>();                \
2886     checker->Filter.Check##name = true;                                        \
2887     checker->Filter.CheckName##name = mgr.getCurrentCheckerName();             \
2888   }                                                                            \
2889                                                                                \
2890   bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
2891 
2892 REGISTER_CHECKER(CStringNullArg)
2893 REGISTER_CHECKER(CStringOutOfBounds)
2894 REGISTER_CHECKER(CStringBufferOverlap)
2895 REGISTER_CHECKER(CStringNotNullTerm)
2896 REGISTER_CHECKER(CStringUninitializedRead)
2897