xref: /freebsd/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
10b57cec5SDimitry Andric //= CStringChecker.cpp - Checks calls to C string functions --------*- C++ -*-//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This defines CStringChecker, which is an assortment of checks on calls
100b57cec5SDimitry Andric // to functions in <string.h>.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "InterCheckerAPI.h"
15*06c3fb27SDimitry Andric #include "clang/Basic/Builtins.h"
160b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h"
175ffd83dbSDimitry Andric #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
180b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
190b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/Checker.h"
200b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/CheckerManager.h"
21349cc55cSDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
220b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
230b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
24fe6060f1SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
250b57cec5SDimitry Andric #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
260b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
270b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
285ffd83dbSDimitry Andric #include "llvm/ADT/StringExtras.h"
290b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
30972a253aSDimitry Andric #include <functional>
31bdd1243dSDimitry Andric #include <optional>
320b57cec5SDimitry Andric 
330b57cec5SDimitry Andric using namespace clang;
340b57cec5SDimitry Andric using namespace ento;
35972a253aSDimitry Andric using namespace std::placeholders;
360b57cec5SDimitry Andric 
370b57cec5SDimitry Andric namespace {
385ffd83dbSDimitry Andric struct AnyArgExpr {
395ffd83dbSDimitry Andric   const Expr *Expression;
405ffd83dbSDimitry Andric   unsigned ArgumentIndex;
415ffd83dbSDimitry Andric };
42*06c3fb27SDimitry Andric struct SourceArgExpr : AnyArgExpr {};
43*06c3fb27SDimitry Andric struct DestinationArgExpr : AnyArgExpr {};
44*06c3fb27SDimitry Andric struct SizeArgExpr : AnyArgExpr {};
455ffd83dbSDimitry Andric 
465ffd83dbSDimitry Andric using ErrorMessage = SmallString<128>;
475ffd83dbSDimitry Andric enum class AccessKind { write, read };
485ffd83dbSDimitry Andric 
495ffd83dbSDimitry Andric static ErrorMessage createOutOfBoundErrorMsg(StringRef FunctionDescription,
505ffd83dbSDimitry Andric                                              AccessKind Access) {
515ffd83dbSDimitry Andric   ErrorMessage Message;
525ffd83dbSDimitry Andric   llvm::raw_svector_ostream Os(Message);
535ffd83dbSDimitry Andric 
545ffd83dbSDimitry Andric   // Function classification like: Memory copy function
555ffd83dbSDimitry Andric   Os << toUppercase(FunctionDescription.front())
565ffd83dbSDimitry Andric      << &FunctionDescription.data()[1];
575ffd83dbSDimitry Andric 
585ffd83dbSDimitry Andric   if (Access == AccessKind::write) {
595ffd83dbSDimitry Andric     Os << " overflows the destination buffer";
605ffd83dbSDimitry Andric   } else { // read access
615ffd83dbSDimitry Andric     Os << " accesses out-of-bound array element";
625ffd83dbSDimitry Andric   }
635ffd83dbSDimitry Andric 
645ffd83dbSDimitry Andric   return Message;
655ffd83dbSDimitry Andric }
665ffd83dbSDimitry Andric 
67480093f4SDimitry Andric enum class ConcatFnKind { none = 0, strcat = 1, strlcat = 2 };
68bdd1243dSDimitry Andric 
69bdd1243dSDimitry Andric enum class CharKind { Regular = 0, Wide };
70bdd1243dSDimitry Andric constexpr CharKind CK_Regular = CharKind::Regular;
71bdd1243dSDimitry Andric constexpr CharKind CK_Wide = CharKind::Wide;
72bdd1243dSDimitry Andric 
73bdd1243dSDimitry Andric static QualType getCharPtrType(ASTContext &Ctx, CharKind CK) {
74bdd1243dSDimitry Andric   return Ctx.getPointerType(CK == CharKind::Regular ? Ctx.CharTy
75bdd1243dSDimitry Andric                                                     : Ctx.WideCharTy);
76bdd1243dSDimitry Andric }
77bdd1243dSDimitry Andric 
780b57cec5SDimitry Andric class CStringChecker : public Checker< eval::Call,
790b57cec5SDimitry Andric                                          check::PreStmt<DeclStmt>,
800b57cec5SDimitry Andric                                          check::LiveSymbols,
810b57cec5SDimitry Andric                                          check::DeadSymbols,
820b57cec5SDimitry Andric                                          check::RegionChanges
830b57cec5SDimitry Andric                                          > {
840b57cec5SDimitry Andric   mutable std::unique_ptr<BugType> BT_Null, BT_Bounds, BT_Overlap,
8581ad6265SDimitry Andric       BT_NotCString, BT_AdditionOverflow, BT_UninitRead;
860b57cec5SDimitry Andric 
87*06c3fb27SDimitry Andric   mutable const char *CurrentFunctionDescription = nullptr;
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric public:
900b57cec5SDimitry Andric   /// The filter is used to filter out the diagnostics which are not enabled by
910b57cec5SDimitry Andric   /// the user.
920b57cec5SDimitry Andric   struct CStringChecksFilter {
9381ad6265SDimitry Andric     bool CheckCStringNullArg = false;
9481ad6265SDimitry Andric     bool CheckCStringOutOfBounds = false;
9581ad6265SDimitry Andric     bool CheckCStringBufferOverlap = false;
9681ad6265SDimitry Andric     bool CheckCStringNotNullTerm = false;
9781ad6265SDimitry Andric     bool CheckCStringUninitializedRead = false;
980b57cec5SDimitry Andric 
99a7dea167SDimitry Andric     CheckerNameRef CheckNameCStringNullArg;
100a7dea167SDimitry Andric     CheckerNameRef CheckNameCStringOutOfBounds;
101a7dea167SDimitry Andric     CheckerNameRef CheckNameCStringBufferOverlap;
102a7dea167SDimitry Andric     CheckerNameRef CheckNameCStringNotNullTerm;
10381ad6265SDimitry Andric     CheckerNameRef CheckNameCStringUninitializedRead;
1040b57cec5SDimitry Andric   };
1050b57cec5SDimitry Andric 
1060b57cec5SDimitry Andric   CStringChecksFilter Filter;
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric   static void *getTag() { static int tag; return &tag; }
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric   bool evalCall(const CallEvent &Call, CheckerContext &C) const;
1110b57cec5SDimitry Andric   void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
1120b57cec5SDimitry Andric   void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
1130b57cec5SDimitry Andric   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric   ProgramStateRef
1160b57cec5SDimitry Andric     checkRegionChanges(ProgramStateRef state,
1170b57cec5SDimitry Andric                        const InvalidatedSymbols *,
1180b57cec5SDimitry Andric                        ArrayRef<const MemRegion *> ExplicitRegions,
1190b57cec5SDimitry Andric                        ArrayRef<const MemRegion *> Regions,
1200b57cec5SDimitry Andric                        const LocationContext *LCtx,
1210b57cec5SDimitry Andric                        const CallEvent *Call) const;
1220b57cec5SDimitry Andric 
123972a253aSDimitry Andric   using FnCheck = std::function<void(const CStringChecker *, CheckerContext &,
124972a253aSDimitry Andric                                      const CallExpr *)>;
125972a253aSDimitry Andric 
1260b57cec5SDimitry Andric   CallDescriptionMap<FnCheck> Callbacks = {
127bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"memcpy"}, 3},
128bdd1243dSDimitry Andric        std::bind(&CStringChecker::evalMemcpy, _1, _2, _3, CK_Regular)},
129bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"wmemcpy"}, 3},
130bdd1243dSDimitry Andric        std::bind(&CStringChecker::evalMemcpy, _1, _2, _3, CK_Wide)},
131bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"mempcpy"}, 3},
132bdd1243dSDimitry Andric        std::bind(&CStringChecker::evalMempcpy, _1, _2, _3, CK_Regular)},
133bdd1243dSDimitry Andric       {{CDF_None, {"wmempcpy"}, 3},
134bdd1243dSDimitry Andric        std::bind(&CStringChecker::evalMempcpy, _1, _2, _3, CK_Wide)},
135bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"memcmp"}, 3},
136bdd1243dSDimitry Andric        std::bind(&CStringChecker::evalMemcmp, _1, _2, _3, CK_Regular)},
137bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"wmemcmp"}, 3},
138bdd1243dSDimitry Andric        std::bind(&CStringChecker::evalMemcmp, _1, _2, _3, CK_Wide)},
139bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"memmove"}, 3},
140bdd1243dSDimitry Andric        std::bind(&CStringChecker::evalMemmove, _1, _2, _3, CK_Regular)},
141bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"wmemmove"}, 3},
142bdd1243dSDimitry Andric        std::bind(&CStringChecker::evalMemmove, _1, _2, _3, CK_Wide)},
143bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"memset"}, 3}, &CStringChecker::evalMemset},
144bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"explicit_memset"}, 3}, &CStringChecker::evalMemset},
145bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"strcpy"}, 2}, &CStringChecker::evalStrcpy},
146bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"strncpy"}, 3}, &CStringChecker::evalStrncpy},
147bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"stpcpy"}, 2}, &CStringChecker::evalStpcpy},
148bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"strlcpy"}, 3}, &CStringChecker::evalStrlcpy},
149bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"strcat"}, 2}, &CStringChecker::evalStrcat},
150bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"strncat"}, 3}, &CStringChecker::evalStrncat},
151bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"strlcat"}, 3}, &CStringChecker::evalStrlcat},
152bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"strlen"}, 1}, &CStringChecker::evalstrLength},
153bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"wcslen"}, 1}, &CStringChecker::evalstrLength},
154bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"strnlen"}, 2}, &CStringChecker::evalstrnLength},
155bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"wcsnlen"}, 2}, &CStringChecker::evalstrnLength},
156bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"strcmp"}, 2}, &CStringChecker::evalStrcmp},
157bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"strncmp"}, 3}, &CStringChecker::evalStrncmp},
158bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"strcasecmp"}, 2}, &CStringChecker::evalStrcasecmp},
159bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"strncasecmp"}, 3},
160bdd1243dSDimitry Andric        &CStringChecker::evalStrncasecmp},
161bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"strsep"}, 2}, &CStringChecker::evalStrsep},
162bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"bcopy"}, 3}, &CStringChecker::evalBcopy},
163bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"bcmp"}, 3},
164bdd1243dSDimitry Andric        std::bind(&CStringChecker::evalMemcmp, _1, _2, _3, CK_Regular)},
165bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"bzero"}, 2}, &CStringChecker::evalBzero},
166bdd1243dSDimitry Andric       {{CDF_MaybeBuiltin, {"explicit_bzero"}, 2}, &CStringChecker::evalBzero},
167*06c3fb27SDimitry Andric       {{CDF_MaybeBuiltin, {"sprintf"}, 2}, &CStringChecker::evalSprintf},
168*06c3fb27SDimitry Andric       {{CDF_MaybeBuiltin, {"snprintf"}, 2}, &CStringChecker::evalSnprintf},
1690b57cec5SDimitry Andric   };
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric   // These require a bit of special handling.
1720b57cec5SDimitry Andric   CallDescription StdCopy{{"std", "copy"}, 3},
1730b57cec5SDimitry Andric       StdCopyBackward{{"std", "copy_backward"}, 3};
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   FnCheck identifyCall(const CallEvent &Call, CheckerContext &C) const;
176bdd1243dSDimitry Andric   void evalMemcpy(CheckerContext &C, const CallExpr *CE, CharKind CK) const;
177bdd1243dSDimitry Andric   void evalMempcpy(CheckerContext &C, const CallExpr *CE, CharKind CK) const;
178bdd1243dSDimitry Andric   void evalMemmove(CheckerContext &C, const CallExpr *CE, CharKind CK) const;
1790b57cec5SDimitry Andric   void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
1800b57cec5SDimitry Andric   void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
1815ffd83dbSDimitry Andric                       ProgramStateRef state, SizeArgExpr Size,
1825ffd83dbSDimitry Andric                       DestinationArgExpr Dest, SourceArgExpr Source,
183bdd1243dSDimitry Andric                       bool Restricted, bool IsMempcpy, CharKind CK) const;
1840b57cec5SDimitry Andric 
185bdd1243dSDimitry Andric   void evalMemcmp(CheckerContext &C, const CallExpr *CE, CharKind CK) const;
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
1880b57cec5SDimitry Andric   void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
1890b57cec5SDimitry Andric   void evalstrLengthCommon(CheckerContext &C,
1900b57cec5SDimitry Andric                            const CallExpr *CE,
1910b57cec5SDimitry Andric                            bool IsStrnlen = false) const;
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
1940b57cec5SDimitry Andric   void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
1950b57cec5SDimitry Andric   void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
1960b57cec5SDimitry Andric   void evalStrlcpy(CheckerContext &C, const CallExpr *CE) const;
197480093f4SDimitry Andric   void evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, bool ReturnEnd,
198480093f4SDimitry Andric                         bool IsBounded, ConcatFnKind appendK,
1990b57cec5SDimitry Andric                         bool returnPtr = true) const;
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric   void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
2020b57cec5SDimitry Andric   void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
2030b57cec5SDimitry Andric   void evalStrlcat(CheckerContext &C, const CallExpr *CE) const;
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric   void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
2060b57cec5SDimitry Andric   void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
2070b57cec5SDimitry Andric   void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
2080b57cec5SDimitry Andric   void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
2090b57cec5SDimitry Andric   void evalStrcmpCommon(CheckerContext &C,
2100b57cec5SDimitry Andric                         const CallExpr *CE,
211480093f4SDimitry Andric                         bool IsBounded = false,
212480093f4SDimitry Andric                         bool IgnoreCase = false) const;
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric   void evalStrsep(CheckerContext &C, const CallExpr *CE) const;
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric   void evalStdCopy(CheckerContext &C, const CallExpr *CE) const;
2170b57cec5SDimitry Andric   void evalStdCopyBackward(CheckerContext &C, const CallExpr *CE) const;
2180b57cec5SDimitry Andric   void evalStdCopyCommon(CheckerContext &C, const CallExpr *CE) const;
2190b57cec5SDimitry Andric   void evalMemset(CheckerContext &C, const CallExpr *CE) const;
2200b57cec5SDimitry Andric   void evalBzero(CheckerContext &C, const CallExpr *CE) const;
2210b57cec5SDimitry Andric 
222*06c3fb27SDimitry Andric   void evalSprintf(CheckerContext &C, const CallExpr *CE) const;
223*06c3fb27SDimitry Andric   void evalSnprintf(CheckerContext &C, const CallExpr *CE) const;
224*06c3fb27SDimitry Andric   void evalSprintfCommon(CheckerContext &C, const CallExpr *CE, bool IsBounded,
225*06c3fb27SDimitry Andric                          bool IsBuiltin) const;
226*06c3fb27SDimitry Andric 
2270b57cec5SDimitry Andric   // Utility methods
2280b57cec5SDimitry Andric   std::pair<ProgramStateRef , ProgramStateRef >
2290b57cec5SDimitry Andric   static assumeZero(CheckerContext &C,
2300b57cec5SDimitry Andric                     ProgramStateRef state, SVal V, QualType Ty);
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric   static ProgramStateRef setCStringLength(ProgramStateRef state,
2330b57cec5SDimitry Andric                                               const MemRegion *MR,
2340b57cec5SDimitry Andric                                               SVal strLength);
2350b57cec5SDimitry Andric   static SVal getCStringLengthForRegion(CheckerContext &C,
2360b57cec5SDimitry Andric                                         ProgramStateRef &state,
2370b57cec5SDimitry Andric                                         const Expr *Ex,
2380b57cec5SDimitry Andric                                         const MemRegion *MR,
2390b57cec5SDimitry Andric                                         bool hypothetical);
2400b57cec5SDimitry Andric   SVal getCStringLength(CheckerContext &C,
2410b57cec5SDimitry Andric                         ProgramStateRef &state,
2420b57cec5SDimitry Andric                         const Expr *Ex,
2430b57cec5SDimitry Andric                         SVal Buf,
2440b57cec5SDimitry Andric                         bool hypothetical = false) const;
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric   const StringLiteral *getCStringLiteral(CheckerContext &C,
2470b57cec5SDimitry Andric                                          ProgramStateRef &state,
2480b57cec5SDimitry Andric                                          const Expr *expr,
2490b57cec5SDimitry Andric                                          SVal val) const;
2500b57cec5SDimitry Andric 
251*06c3fb27SDimitry Andric   /// Invalidate the destination buffer determined by characters copied.
252*06c3fb27SDimitry Andric   static ProgramStateRef
253*06c3fb27SDimitry Andric   invalidateDestinationBufferBySize(CheckerContext &C, ProgramStateRef S,
254*06c3fb27SDimitry Andric                                     const Expr *BufE, SVal BufV, SVal SizeV,
255*06c3fb27SDimitry Andric                                     QualType SizeTy);
256*06c3fb27SDimitry Andric 
257*06c3fb27SDimitry Andric   /// Operation never overflows, do not invalidate the super region.
258*06c3fb27SDimitry Andric   static ProgramStateRef invalidateDestinationBufferNeverOverflows(
259*06c3fb27SDimitry Andric       CheckerContext &C, ProgramStateRef S, const Expr *BufE, SVal BufV);
260*06c3fb27SDimitry Andric 
261*06c3fb27SDimitry Andric   /// We do not know whether the operation can overflow (e.g. size is unknown),
262*06c3fb27SDimitry Andric   /// invalidate the super region and escape related pointers.
263*06c3fb27SDimitry Andric   static ProgramStateRef invalidateDestinationBufferAlwaysEscapeSuperRegion(
264*06c3fb27SDimitry Andric       CheckerContext &C, ProgramStateRef S, const Expr *BufE, SVal BufV);
265*06c3fb27SDimitry Andric 
266*06c3fb27SDimitry Andric   /// Invalidate the source buffer for escaping pointers.
267*06c3fb27SDimitry Andric   static ProgramStateRef invalidateSourceBuffer(CheckerContext &C,
268*06c3fb27SDimitry Andric                                                 ProgramStateRef S,
269*06c3fb27SDimitry Andric                                                 const Expr *BufE, SVal BufV);
270*06c3fb27SDimitry Andric 
271*06c3fb27SDimitry Andric   /// @param InvalidationTraitOperations Determine how to invlidate the
272*06c3fb27SDimitry Andric   /// MemRegion by setting the invalidation traits. Return true to cause pointer
273*06c3fb27SDimitry Andric   /// escape, or false otherwise.
274*06c3fb27SDimitry Andric   static ProgramStateRef invalidateBufferAux(
275*06c3fb27SDimitry Andric       CheckerContext &C, ProgramStateRef State, const Expr *Ex, SVal V,
276*06c3fb27SDimitry Andric       llvm::function_ref<bool(RegionAndSymbolInvalidationTraits &,
277*06c3fb27SDimitry Andric                               const MemRegion *)>
278*06c3fb27SDimitry Andric           InvalidationTraitOperations);
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric   static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
2810b57cec5SDimitry Andric                               const MemRegion *MR);
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric   static bool memsetAux(const Expr *DstBuffer, SVal CharE,
2840b57cec5SDimitry Andric                         const Expr *Size, CheckerContext &C,
2850b57cec5SDimitry Andric                         ProgramStateRef &State);
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric   // Re-usable checks
2885ffd83dbSDimitry Andric   ProgramStateRef checkNonNull(CheckerContext &C, ProgramStateRef State,
2895ffd83dbSDimitry Andric                                AnyArgExpr Arg, SVal l) const;
2905ffd83dbSDimitry Andric   ProgramStateRef CheckLocation(CheckerContext &C, ProgramStateRef state,
2915ffd83dbSDimitry Andric                                 AnyArgExpr Buffer, SVal Element,
292bdd1243dSDimitry Andric                                 AccessKind Access,
293bdd1243dSDimitry Andric                                 CharKind CK = CharKind::Regular) const;
2945ffd83dbSDimitry Andric   ProgramStateRef CheckBufferAccess(CheckerContext &C, ProgramStateRef State,
2955ffd83dbSDimitry Andric                                     AnyArgExpr Buffer, SizeArgExpr Size,
296972a253aSDimitry Andric                                     AccessKind Access,
297bdd1243dSDimitry Andric                                     CharKind CK = CharKind::Regular) const;
2985ffd83dbSDimitry Andric   ProgramStateRef CheckOverlap(CheckerContext &C, ProgramStateRef state,
2995ffd83dbSDimitry Andric                                SizeArgExpr Size, AnyArgExpr First,
300bdd1243dSDimitry Andric                                AnyArgExpr Second,
301bdd1243dSDimitry Andric                                CharKind CK = CharKind::Regular) const;
3020b57cec5SDimitry Andric   void emitOverlapBug(CheckerContext &C,
3030b57cec5SDimitry Andric                       ProgramStateRef state,
3040b57cec5SDimitry Andric                       const Stmt *First,
3050b57cec5SDimitry Andric                       const Stmt *Second) const;
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric   void emitNullArgBug(CheckerContext &C, ProgramStateRef State, const Stmt *S,
3080b57cec5SDimitry Andric                       StringRef WarningMsg) const;
3090b57cec5SDimitry Andric   void emitOutOfBoundsBug(CheckerContext &C, ProgramStateRef State,
3100b57cec5SDimitry Andric                           const Stmt *S, StringRef WarningMsg) const;
3110b57cec5SDimitry Andric   void emitNotCStringBug(CheckerContext &C, ProgramStateRef State,
3120b57cec5SDimitry Andric                          const Stmt *S, StringRef WarningMsg) const;
3130b57cec5SDimitry Andric   void emitAdditionOverflowBug(CheckerContext &C, ProgramStateRef State) const;
31481ad6265SDimitry Andric   void emitUninitializedReadBug(CheckerContext &C, ProgramStateRef State,
31581ad6265SDimitry Andric                              const Expr *E) const;
3160b57cec5SDimitry Andric   ProgramStateRef checkAdditionOverflow(CheckerContext &C,
3170b57cec5SDimitry Andric                                             ProgramStateRef state,
3180b57cec5SDimitry Andric                                             NonLoc left,
3190b57cec5SDimitry Andric                                             NonLoc right) const;
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric   // Return true if the destination buffer of the copy function may be in bound.
3220b57cec5SDimitry Andric   // Expects SVal of Size to be positive and unsigned.
3230b57cec5SDimitry Andric   // Expects SVal of FirstBuf to be a FieldRegion.
324*06c3fb27SDimitry Andric   static bool isFirstBufInBound(CheckerContext &C, ProgramStateRef State,
325*06c3fb27SDimitry Andric                                 SVal BufVal, QualType BufTy, SVal LengthVal,
326*06c3fb27SDimitry Andric                                 QualType LengthTy);
3270b57cec5SDimitry Andric };
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric } //end anonymous namespace
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
3340b57cec5SDimitry Andric // Individual checks and utility methods.
3350b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
3360b57cec5SDimitry Andric 
3370b57cec5SDimitry Andric std::pair<ProgramStateRef , ProgramStateRef >
3380b57cec5SDimitry Andric CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
3390b57cec5SDimitry Andric                            QualType Ty) {
340bdd1243dSDimitry Andric   std::optional<DefinedSVal> val = V.getAs<DefinedSVal>();
3410b57cec5SDimitry Andric   if (!val)
3420b57cec5SDimitry Andric     return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric   SValBuilder &svalBuilder = C.getSValBuilder();
3450b57cec5SDimitry Andric   DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
3460b57cec5SDimitry Andric   return state->assume(svalBuilder.evalEQ(state, *val, zero));
3470b57cec5SDimitry Andric }
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
3505ffd83dbSDimitry Andric                                              ProgramStateRef State,
3515ffd83dbSDimitry Andric                                              AnyArgExpr Arg, SVal l) const {
3520b57cec5SDimitry Andric   // If a previous check has failed, propagate the failure.
3535ffd83dbSDimitry Andric   if (!State)
3540b57cec5SDimitry Andric     return nullptr;
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric   ProgramStateRef stateNull, stateNonNull;
3575ffd83dbSDimitry Andric   std::tie(stateNull, stateNonNull) =
3585ffd83dbSDimitry Andric       assumeZero(C, State, l, Arg.Expression->getType());
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric   if (stateNull && !stateNonNull) {
3610b57cec5SDimitry Andric     if (Filter.CheckCStringNullArg) {
3620b57cec5SDimitry Andric       SmallString<80> buf;
363a7dea167SDimitry Andric       llvm::raw_svector_ostream OS(buf);
3640b57cec5SDimitry Andric       assert(CurrentFunctionDescription);
3655ffd83dbSDimitry Andric       OS << "Null pointer passed as " << (Arg.ArgumentIndex + 1)
3665ffd83dbSDimitry Andric          << llvm::getOrdinalSuffix(Arg.ArgumentIndex + 1) << " argument to "
367480093f4SDimitry Andric          << CurrentFunctionDescription;
3680b57cec5SDimitry Andric 
3695ffd83dbSDimitry Andric       emitNullArgBug(C, stateNull, Arg.Expression, OS.str());
3700b57cec5SDimitry Andric     }
3710b57cec5SDimitry Andric     return nullptr;
3720b57cec5SDimitry Andric   }
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric   // From here on, assume that the value is non-null.
3750b57cec5SDimitry Andric   assert(stateNonNull);
3760b57cec5SDimitry Andric   return stateNonNull;
3770b57cec5SDimitry Andric }
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric // FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
3800b57cec5SDimitry Andric ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
3810b57cec5SDimitry Andric                                               ProgramStateRef state,
3825ffd83dbSDimitry Andric                                               AnyArgExpr Buffer, SVal Element,
383972a253aSDimitry Andric                                               AccessKind Access,
384bdd1243dSDimitry Andric                                               CharKind CK) const {
3855ffd83dbSDimitry Andric 
3860b57cec5SDimitry Andric   // If a previous check has failed, propagate the failure.
3870b57cec5SDimitry Andric   if (!state)
3880b57cec5SDimitry Andric     return nullptr;
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric   // Check for out of bound array element access.
3915ffd83dbSDimitry Andric   const MemRegion *R = Element.getAsRegion();
3920b57cec5SDimitry Andric   if (!R)
3930b57cec5SDimitry Andric     return state;
3940b57cec5SDimitry Andric 
3955ffd83dbSDimitry Andric   const auto *ER = dyn_cast<ElementRegion>(R);
3960b57cec5SDimitry Andric   if (!ER)
3970b57cec5SDimitry Andric     return state;
3980b57cec5SDimitry Andric 
399972a253aSDimitry Andric   SValBuilder &svalBuilder = C.getSValBuilder();
400972a253aSDimitry Andric   ASTContext &Ctx = svalBuilder.getContext();
401972a253aSDimitry Andric 
402972a253aSDimitry Andric   // Get the index of the accessed element.
403972a253aSDimitry Andric   NonLoc Idx = ER->getIndex();
404972a253aSDimitry Andric 
405bdd1243dSDimitry Andric   if (CK == CharKind::Regular) {
406972a253aSDimitry Andric     if (ER->getValueType() != Ctx.CharTy)
4070b57cec5SDimitry Andric       return state;
408972a253aSDimitry Andric   } else {
409972a253aSDimitry Andric     if (ER->getValueType() != Ctx.WideCharTy)
410972a253aSDimitry Andric       return state;
411972a253aSDimitry Andric 
412972a253aSDimitry Andric     QualType SizeTy = Ctx.getSizeType();
413972a253aSDimitry Andric     NonLoc WideSize =
414972a253aSDimitry Andric         svalBuilder
415972a253aSDimitry Andric             .makeIntVal(Ctx.getTypeSizeInChars(Ctx.WideCharTy).getQuantity(),
416972a253aSDimitry Andric                         SizeTy)
417972a253aSDimitry Andric             .castAs<NonLoc>();
418972a253aSDimitry Andric     SVal Offset = svalBuilder.evalBinOpNN(state, BO_Mul, Idx, WideSize, SizeTy);
419972a253aSDimitry Andric     if (Offset.isUnknown())
420972a253aSDimitry Andric       return state;
421972a253aSDimitry Andric     Idx = Offset.castAs<NonLoc>();
422972a253aSDimitry Andric   }
4230b57cec5SDimitry Andric 
4240b57cec5SDimitry Andric   // Get the size of the array.
4255ffd83dbSDimitry Andric   const auto *superReg = cast<SubRegion>(ER->getSuperRegion());
4265ffd83dbSDimitry Andric   DefinedOrUnknownSVal Size =
427fe6060f1SDimitry Andric       getDynamicExtent(state, superReg, C.getSValBuilder());
4280b57cec5SDimitry Andric 
42981ad6265SDimitry Andric   ProgramStateRef StInBound, StOutBound;
43081ad6265SDimitry Andric   std::tie(StInBound, StOutBound) = state->assumeInBoundDual(Idx, Size);
4310b57cec5SDimitry Andric   if (StOutBound && !StInBound) {
4320b57cec5SDimitry Andric     // These checks are either enabled by the CString out-of-bounds checker
4330b57cec5SDimitry Andric     // explicitly or implicitly by the Malloc checker.
4340b57cec5SDimitry Andric     // In the latter case we only do modeling but do not emit warning.
4350b57cec5SDimitry Andric     if (!Filter.CheckCStringOutOfBounds)
4360b57cec5SDimitry Andric       return nullptr;
4370b57cec5SDimitry Andric 
4385ffd83dbSDimitry Andric     // Emit a bug report.
4395ffd83dbSDimitry Andric     ErrorMessage Message =
4405ffd83dbSDimitry Andric         createOutOfBoundErrorMsg(CurrentFunctionDescription, Access);
4415ffd83dbSDimitry Andric     emitOutOfBoundsBug(C, StOutBound, Buffer.Expression, Message);
4420b57cec5SDimitry Andric     return nullptr;
4430b57cec5SDimitry Andric   }
4440b57cec5SDimitry Andric 
44581ad6265SDimitry Andric   // Ensure that we wouldn't read uninitialized value.
44681ad6265SDimitry Andric   if (Access == AccessKind::read) {
44781ad6265SDimitry Andric     if (Filter.CheckCStringUninitializedRead &&
44881ad6265SDimitry Andric         StInBound->getSVal(ER).isUndef()) {
44981ad6265SDimitry Andric       emitUninitializedReadBug(C, StInBound, Buffer.Expression);
45081ad6265SDimitry Andric       return nullptr;
45181ad6265SDimitry Andric     }
45281ad6265SDimitry Andric   }
45381ad6265SDimitry Andric 
4540b57cec5SDimitry Andric   // Array bound check succeeded.  From this point forward the array bound
4550b57cec5SDimitry Andric   // should always succeed.
4560b57cec5SDimitry Andric   return StInBound;
4570b57cec5SDimitry Andric }
4580b57cec5SDimitry Andric 
459972a253aSDimitry Andric ProgramStateRef
460972a253aSDimitry Andric CStringChecker::CheckBufferAccess(CheckerContext &C, ProgramStateRef State,
461972a253aSDimitry Andric                                   AnyArgExpr Buffer, SizeArgExpr Size,
462bdd1243dSDimitry Andric                                   AccessKind Access, CharKind CK) const {
4630b57cec5SDimitry Andric   // If a previous check has failed, propagate the failure.
4645ffd83dbSDimitry Andric   if (!State)
4650b57cec5SDimitry Andric     return nullptr;
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric   SValBuilder &svalBuilder = C.getSValBuilder();
4680b57cec5SDimitry Andric   ASTContext &Ctx = svalBuilder.getContext();
4690b57cec5SDimitry Andric 
4705ffd83dbSDimitry Andric   QualType SizeTy = Size.Expression->getType();
471bdd1243dSDimitry Andric   QualType PtrTy = getCharPtrType(Ctx, CK);
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric   // Check that the first buffer is non-null.
4745ffd83dbSDimitry Andric   SVal BufVal = C.getSVal(Buffer.Expression);
4755ffd83dbSDimitry Andric   State = checkNonNull(C, State, Buffer, BufVal);
4765ffd83dbSDimitry Andric   if (!State)
4770b57cec5SDimitry Andric     return nullptr;
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric   // If out-of-bounds checking is turned off, skip the rest.
4800b57cec5SDimitry Andric   if (!Filter.CheckCStringOutOfBounds)
4815ffd83dbSDimitry Andric     return State;
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric   // Get the access length and make sure it is known.
4840b57cec5SDimitry Andric   // FIXME: This assumes the caller has already checked that the access length
4850b57cec5SDimitry Andric   // is positive. And that it's unsigned.
4865ffd83dbSDimitry Andric   SVal LengthVal = C.getSVal(Size.Expression);
487bdd1243dSDimitry Andric   std::optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
4880b57cec5SDimitry Andric   if (!Length)
4895ffd83dbSDimitry Andric     return State;
4900b57cec5SDimitry Andric 
4910b57cec5SDimitry Andric   // Compute the offset of the last element to be accessed: size-1.
4925ffd83dbSDimitry Andric   NonLoc One = svalBuilder.makeIntVal(1, SizeTy).castAs<NonLoc>();
4935ffd83dbSDimitry Andric   SVal Offset = svalBuilder.evalBinOpNN(State, BO_Sub, *Length, One, SizeTy);
4940b57cec5SDimitry Andric   if (Offset.isUnknown())
4950b57cec5SDimitry Andric     return nullptr;
4960b57cec5SDimitry Andric   NonLoc LastOffset = Offset.castAs<NonLoc>();
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric   // Check that the first buffer is sufficiently long.
4995ffd83dbSDimitry Andric   SVal BufStart =
5005ffd83dbSDimitry Andric       svalBuilder.evalCast(BufVal, PtrTy, Buffer.Expression->getType());
501bdd1243dSDimitry Andric   if (std::optional<Loc> BufLoc = BufStart.getAs<Loc>()) {
5020b57cec5SDimitry Andric 
5035ffd83dbSDimitry Andric     SVal BufEnd =
5045ffd83dbSDimitry Andric         svalBuilder.evalBinOpLN(State, BO_Add, *BufLoc, LastOffset, PtrTy);
505bdd1243dSDimitry Andric     State = CheckLocation(C, State, Buffer, BufEnd, Access, CK);
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric     // If the buffer isn't large enough, abort.
5085ffd83dbSDimitry Andric     if (!State)
5090b57cec5SDimitry Andric       return nullptr;
5100b57cec5SDimitry Andric   }
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric   // Large enough or not, return this state!
5135ffd83dbSDimitry Andric   return State;
5140b57cec5SDimitry Andric }
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
5170b57cec5SDimitry Andric                                              ProgramStateRef state,
5185ffd83dbSDimitry Andric                                              SizeArgExpr Size, AnyArgExpr First,
519972a253aSDimitry Andric                                              AnyArgExpr Second,
520bdd1243dSDimitry Andric                                              CharKind CK) const {
5210b57cec5SDimitry Andric   if (!Filter.CheckCStringBufferOverlap)
5220b57cec5SDimitry Andric     return state;
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   // Do a simple check for overlap: if the two arguments are from the same
5250b57cec5SDimitry Andric   // buffer, see if the end of the first is greater than the start of the second
5260b57cec5SDimitry Andric   // or vice versa.
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric   // If a previous check has failed, propagate the failure.
5290b57cec5SDimitry Andric   if (!state)
5300b57cec5SDimitry Andric     return nullptr;
5310b57cec5SDimitry Andric 
5320b57cec5SDimitry Andric   ProgramStateRef stateTrue, stateFalse;
5330b57cec5SDimitry Andric 
53481ad6265SDimitry Andric   // Assume different address spaces cannot overlap.
53581ad6265SDimitry Andric   if (First.Expression->getType()->getPointeeType().getAddressSpace() !=
53681ad6265SDimitry Andric       Second.Expression->getType()->getPointeeType().getAddressSpace())
53781ad6265SDimitry Andric     return state;
53881ad6265SDimitry Andric 
5390b57cec5SDimitry Andric   // Get the buffer values and make sure they're known locations.
5400b57cec5SDimitry Andric   const LocationContext *LCtx = C.getLocationContext();
5415ffd83dbSDimitry Andric   SVal firstVal = state->getSVal(First.Expression, LCtx);
5425ffd83dbSDimitry Andric   SVal secondVal = state->getSVal(Second.Expression, LCtx);
5430b57cec5SDimitry Andric 
544bdd1243dSDimitry Andric   std::optional<Loc> firstLoc = firstVal.getAs<Loc>();
5450b57cec5SDimitry Andric   if (!firstLoc)
5460b57cec5SDimitry Andric     return state;
5470b57cec5SDimitry Andric 
548bdd1243dSDimitry Andric   std::optional<Loc> secondLoc = secondVal.getAs<Loc>();
5490b57cec5SDimitry Andric   if (!secondLoc)
5500b57cec5SDimitry Andric     return state;
5510b57cec5SDimitry Andric 
5520b57cec5SDimitry Andric   // Are the two values the same?
5530b57cec5SDimitry Andric   SValBuilder &svalBuilder = C.getSValBuilder();
5540b57cec5SDimitry Andric   std::tie(stateTrue, stateFalse) =
5550b57cec5SDimitry Andric       state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
5560b57cec5SDimitry Andric 
5570b57cec5SDimitry Andric   if (stateTrue && !stateFalse) {
5580b57cec5SDimitry Andric     // If the values are known to be equal, that's automatically an overlap.
5595ffd83dbSDimitry Andric     emitOverlapBug(C, stateTrue, First.Expression, Second.Expression);
5600b57cec5SDimitry Andric     return nullptr;
5610b57cec5SDimitry Andric   }
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric   // assume the two expressions are not equal.
5640b57cec5SDimitry Andric   assert(stateFalse);
5650b57cec5SDimitry Andric   state = stateFalse;
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric   // Which value comes first?
5680b57cec5SDimitry Andric   QualType cmpTy = svalBuilder.getConditionType();
5695ffd83dbSDimitry Andric   SVal reverse =
5705ffd83dbSDimitry Andric       svalBuilder.evalBinOpLL(state, BO_GT, *firstLoc, *secondLoc, cmpTy);
571bdd1243dSDimitry Andric   std::optional<DefinedOrUnknownSVal> reverseTest =
5720b57cec5SDimitry Andric       reverse.getAs<DefinedOrUnknownSVal>();
5730b57cec5SDimitry Andric   if (!reverseTest)
5740b57cec5SDimitry Andric     return state;
5750b57cec5SDimitry Andric 
5760b57cec5SDimitry Andric   std::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
5770b57cec5SDimitry Andric   if (stateTrue) {
5780b57cec5SDimitry Andric     if (stateFalse) {
5790b57cec5SDimitry Andric       // If we don't know which one comes first, we can't perform this test.
5800b57cec5SDimitry Andric       return state;
5810b57cec5SDimitry Andric     } else {
5820b57cec5SDimitry Andric       // Switch the values so that firstVal is before secondVal.
5830b57cec5SDimitry Andric       std::swap(firstLoc, secondLoc);
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric       // Switch the Exprs as well, so that they still correspond.
5860b57cec5SDimitry Andric       std::swap(First, Second);
5870b57cec5SDimitry Andric     }
5880b57cec5SDimitry Andric   }
5890b57cec5SDimitry Andric 
5900b57cec5SDimitry Andric   // Get the length, and make sure it too is known.
5915ffd83dbSDimitry Andric   SVal LengthVal = state->getSVal(Size.Expression, LCtx);
592bdd1243dSDimitry Andric   std::optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
5930b57cec5SDimitry Andric   if (!Length)
5940b57cec5SDimitry Andric     return state;
5950b57cec5SDimitry Andric 
5960b57cec5SDimitry Andric   // Convert the first buffer's start address to char*.
5970b57cec5SDimitry Andric   // Bail out if the cast fails.
5980b57cec5SDimitry Andric   ASTContext &Ctx = svalBuilder.getContext();
599bdd1243dSDimitry Andric   QualType CharPtrTy = getCharPtrType(Ctx, CK);
6005ffd83dbSDimitry Andric   SVal FirstStart =
6015ffd83dbSDimitry Andric       svalBuilder.evalCast(*firstLoc, CharPtrTy, First.Expression->getType());
602bdd1243dSDimitry Andric   std::optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>();
6030b57cec5SDimitry Andric   if (!FirstStartLoc)
6040b57cec5SDimitry Andric     return state;
6050b57cec5SDimitry Andric 
6060b57cec5SDimitry Andric   // Compute the end of the first buffer. Bail out if THAT fails.
6075ffd83dbSDimitry Andric   SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add, *FirstStartLoc,
6085ffd83dbSDimitry Andric                                           *Length, CharPtrTy);
609bdd1243dSDimitry Andric   std::optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>();
6100b57cec5SDimitry Andric   if (!FirstEndLoc)
6110b57cec5SDimitry Andric     return state;
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric   // Is the end of the first buffer past the start of the second buffer?
6145ffd83dbSDimitry Andric   SVal Overlap =
6155ffd83dbSDimitry Andric       svalBuilder.evalBinOpLL(state, BO_GT, *FirstEndLoc, *secondLoc, cmpTy);
616bdd1243dSDimitry Andric   std::optional<DefinedOrUnknownSVal> OverlapTest =
6170b57cec5SDimitry Andric       Overlap.getAs<DefinedOrUnknownSVal>();
6180b57cec5SDimitry Andric   if (!OverlapTest)
6190b57cec5SDimitry Andric     return state;
6200b57cec5SDimitry Andric 
6210b57cec5SDimitry Andric   std::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
6220b57cec5SDimitry Andric 
6230b57cec5SDimitry Andric   if (stateTrue && !stateFalse) {
6240b57cec5SDimitry Andric     // Overlap!
6255ffd83dbSDimitry Andric     emitOverlapBug(C, stateTrue, First.Expression, Second.Expression);
6260b57cec5SDimitry Andric     return nullptr;
6270b57cec5SDimitry Andric   }
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric   // assume the two expressions don't overlap.
6300b57cec5SDimitry Andric   assert(stateFalse);
6310b57cec5SDimitry Andric   return stateFalse;
6320b57cec5SDimitry Andric }
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
6350b57cec5SDimitry Andric                                   const Stmt *First, const Stmt *Second) const {
6360b57cec5SDimitry Andric   ExplodedNode *N = C.generateErrorNode(state);
6370b57cec5SDimitry Andric   if (!N)
6380b57cec5SDimitry Andric     return;
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric   if (!BT_Overlap)
6410b57cec5SDimitry Andric     BT_Overlap.reset(new BugType(Filter.CheckNameCStringBufferOverlap,
6420b57cec5SDimitry Andric                                  categories::UnixAPI, "Improper arguments"));
6430b57cec5SDimitry Andric 
6440b57cec5SDimitry Andric   // Generate a report for this bug.
645a7dea167SDimitry Andric   auto report = std::make_unique<PathSensitiveBugReport>(
6460b57cec5SDimitry Andric       *BT_Overlap, "Arguments must not be overlapping buffers", N);
6470b57cec5SDimitry Andric   report->addRange(First->getSourceRange());
6480b57cec5SDimitry Andric   report->addRange(Second->getSourceRange());
6490b57cec5SDimitry Andric 
6500b57cec5SDimitry Andric   C.emitReport(std::move(report));
6510b57cec5SDimitry Andric }
6520b57cec5SDimitry Andric 
6530b57cec5SDimitry Andric void CStringChecker::emitNullArgBug(CheckerContext &C, ProgramStateRef State,
6540b57cec5SDimitry Andric                                     const Stmt *S, StringRef WarningMsg) const {
6550b57cec5SDimitry Andric   if (ExplodedNode *N = C.generateErrorNode(State)) {
6560b57cec5SDimitry Andric     if (!BT_Null)
6570b57cec5SDimitry Andric       BT_Null.reset(new BuiltinBug(
6580b57cec5SDimitry Andric           Filter.CheckNameCStringNullArg, categories::UnixAPI,
6590b57cec5SDimitry Andric           "Null pointer argument in call to byte string function"));
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric     BuiltinBug *BT = static_cast<BuiltinBug *>(BT_Null.get());
662a7dea167SDimitry Andric     auto Report = std::make_unique<PathSensitiveBugReport>(*BT, WarningMsg, N);
6630b57cec5SDimitry Andric     Report->addRange(S->getSourceRange());
6640b57cec5SDimitry Andric     if (const auto *Ex = dyn_cast<Expr>(S))
6650b57cec5SDimitry Andric       bugreporter::trackExpressionValue(N, Ex, *Report);
6660b57cec5SDimitry Andric     C.emitReport(std::move(Report));
6670b57cec5SDimitry Andric   }
6680b57cec5SDimitry Andric }
6690b57cec5SDimitry Andric 
67081ad6265SDimitry Andric void CStringChecker::emitUninitializedReadBug(CheckerContext &C,
67181ad6265SDimitry Andric                                               ProgramStateRef State,
67281ad6265SDimitry Andric                                               const Expr *E) const {
67381ad6265SDimitry Andric   if (ExplodedNode *N = C.generateErrorNode(State)) {
67481ad6265SDimitry Andric     const char *Msg =
67581ad6265SDimitry Andric         "Bytes string function accesses uninitialized/garbage values";
67681ad6265SDimitry Andric     if (!BT_UninitRead)
67781ad6265SDimitry Andric       BT_UninitRead.reset(
67881ad6265SDimitry Andric           new BuiltinBug(Filter.CheckNameCStringUninitializedRead,
67981ad6265SDimitry Andric                          "Accessing unitialized/garbage values", Msg));
68081ad6265SDimitry Andric 
68181ad6265SDimitry Andric     BuiltinBug *BT = static_cast<BuiltinBug *>(BT_UninitRead.get());
68281ad6265SDimitry Andric 
68381ad6265SDimitry Andric     auto Report = std::make_unique<PathSensitiveBugReport>(*BT, Msg, N);
68481ad6265SDimitry Andric     Report->addRange(E->getSourceRange());
68581ad6265SDimitry Andric     bugreporter::trackExpressionValue(N, E, *Report);
68681ad6265SDimitry Andric     C.emitReport(std::move(Report));
68781ad6265SDimitry Andric   }
68881ad6265SDimitry Andric }
68981ad6265SDimitry Andric 
6900b57cec5SDimitry Andric void CStringChecker::emitOutOfBoundsBug(CheckerContext &C,
6910b57cec5SDimitry Andric                                         ProgramStateRef State, const Stmt *S,
6920b57cec5SDimitry Andric                                         StringRef WarningMsg) const {
6930b57cec5SDimitry Andric   if (ExplodedNode *N = C.generateErrorNode(State)) {
6940b57cec5SDimitry Andric     if (!BT_Bounds)
6950b57cec5SDimitry Andric       BT_Bounds.reset(new BuiltinBug(
6960b57cec5SDimitry Andric           Filter.CheckCStringOutOfBounds ? Filter.CheckNameCStringOutOfBounds
6970b57cec5SDimitry Andric                                          : Filter.CheckNameCStringNullArg,
6980b57cec5SDimitry Andric           "Out-of-bound array access",
6990b57cec5SDimitry Andric           "Byte string function accesses out-of-bound array element"));
7000b57cec5SDimitry Andric 
7010b57cec5SDimitry Andric     BuiltinBug *BT = static_cast<BuiltinBug *>(BT_Bounds.get());
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric     // FIXME: It would be nice to eventually make this diagnostic more clear,
7040b57cec5SDimitry Andric     // e.g., by referencing the original declaration or by saying *why* this
7050b57cec5SDimitry Andric     // reference is outside the range.
706a7dea167SDimitry Andric     auto Report = std::make_unique<PathSensitiveBugReport>(*BT, WarningMsg, N);
7070b57cec5SDimitry Andric     Report->addRange(S->getSourceRange());
7080b57cec5SDimitry Andric     C.emitReport(std::move(Report));
7090b57cec5SDimitry Andric   }
7100b57cec5SDimitry Andric }
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric void CStringChecker::emitNotCStringBug(CheckerContext &C, ProgramStateRef State,
7130b57cec5SDimitry Andric                                        const Stmt *S,
7140b57cec5SDimitry Andric                                        StringRef WarningMsg) const {
7150b57cec5SDimitry Andric   if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) {
7160b57cec5SDimitry Andric     if (!BT_NotCString)
7170b57cec5SDimitry Andric       BT_NotCString.reset(new BuiltinBug(
7180b57cec5SDimitry Andric           Filter.CheckNameCStringNotNullTerm, categories::UnixAPI,
7190b57cec5SDimitry Andric           "Argument is not a null-terminated string."));
7200b57cec5SDimitry Andric 
721a7dea167SDimitry Andric     auto Report =
722a7dea167SDimitry Andric         std::make_unique<PathSensitiveBugReport>(*BT_NotCString, WarningMsg, N);
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric     Report->addRange(S->getSourceRange());
7250b57cec5SDimitry Andric     C.emitReport(std::move(Report));
7260b57cec5SDimitry Andric   }
7270b57cec5SDimitry Andric }
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry Andric void CStringChecker::emitAdditionOverflowBug(CheckerContext &C,
7300b57cec5SDimitry Andric                                              ProgramStateRef State) const {
7310b57cec5SDimitry Andric   if (ExplodedNode *N = C.generateErrorNode(State)) {
73281ad6265SDimitry Andric     if (!BT_AdditionOverflow)
73381ad6265SDimitry Andric       BT_AdditionOverflow.reset(
7340b57cec5SDimitry Andric           new BuiltinBug(Filter.CheckNameCStringOutOfBounds, "API",
7350b57cec5SDimitry Andric                          "Sum of expressions causes overflow."));
7360b57cec5SDimitry Andric 
7370b57cec5SDimitry Andric     // This isn't a great error message, but this should never occur in real
7380b57cec5SDimitry Andric     // code anyway -- you'd have to create a buffer longer than a size_t can
7390b57cec5SDimitry Andric     // represent, which is sort of a contradiction.
7400b57cec5SDimitry Andric     const char *WarningMsg =
7410b57cec5SDimitry Andric         "This expression will create a string whose length is too big to "
7420b57cec5SDimitry Andric         "be represented as a size_t";
7430b57cec5SDimitry Andric 
74481ad6265SDimitry Andric     auto Report = std::make_unique<PathSensitiveBugReport>(*BT_AdditionOverflow,
74581ad6265SDimitry Andric                                                            WarningMsg, N);
7460b57cec5SDimitry Andric     C.emitReport(std::move(Report));
7470b57cec5SDimitry Andric   }
7480b57cec5SDimitry Andric }
7490b57cec5SDimitry Andric 
7500b57cec5SDimitry Andric ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
7510b57cec5SDimitry Andric                                                      ProgramStateRef state,
7520b57cec5SDimitry Andric                                                      NonLoc left,
7530b57cec5SDimitry Andric                                                      NonLoc right) const {
7540b57cec5SDimitry Andric   // If out-of-bounds checking is turned off, skip the rest.
7550b57cec5SDimitry Andric   if (!Filter.CheckCStringOutOfBounds)
7560b57cec5SDimitry Andric     return state;
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric   // If a previous check has failed, propagate the failure.
7590b57cec5SDimitry Andric   if (!state)
7600b57cec5SDimitry Andric     return nullptr;
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric   SValBuilder &svalBuilder = C.getSValBuilder();
7630b57cec5SDimitry Andric   BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
7640b57cec5SDimitry Andric 
7650b57cec5SDimitry Andric   QualType sizeTy = svalBuilder.getContext().getSizeType();
7660b57cec5SDimitry Andric   const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
7670b57cec5SDimitry Andric   NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
7680b57cec5SDimitry Andric 
7690b57cec5SDimitry Andric   SVal maxMinusRight;
77081ad6265SDimitry Andric   if (isa<nonloc::ConcreteInt>(right)) {
7710b57cec5SDimitry Andric     maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
7720b57cec5SDimitry Andric                                                  sizeTy);
7730b57cec5SDimitry Andric   } else {
7740b57cec5SDimitry Andric     // Try switching the operands. (The order of these two assignments is
7750b57cec5SDimitry Andric     // important!)
7760b57cec5SDimitry Andric     maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
7770b57cec5SDimitry Andric                                             sizeTy);
7780b57cec5SDimitry Andric     left = right;
7790b57cec5SDimitry Andric   }
7800b57cec5SDimitry Andric 
781bdd1243dSDimitry Andric   if (std::optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) {
7820b57cec5SDimitry Andric     QualType cmpTy = svalBuilder.getConditionType();
7830b57cec5SDimitry Andric     // If left > max - right, we have an overflow.
7840b57cec5SDimitry Andric     SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
7850b57cec5SDimitry Andric                                                 *maxMinusRightNL, cmpTy);
7860b57cec5SDimitry Andric 
7870b57cec5SDimitry Andric     ProgramStateRef stateOverflow, stateOkay;
7880b57cec5SDimitry Andric     std::tie(stateOverflow, stateOkay) =
7890b57cec5SDimitry Andric       state->assume(willOverflow.castAs<DefinedOrUnknownSVal>());
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric     if (stateOverflow && !stateOkay) {
7920b57cec5SDimitry Andric       // We have an overflow. Emit a bug report.
7930b57cec5SDimitry Andric       emitAdditionOverflowBug(C, stateOverflow);
7940b57cec5SDimitry Andric       return nullptr;
7950b57cec5SDimitry Andric     }
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric     // From now on, assume an overflow didn't occur.
7980b57cec5SDimitry Andric     assert(stateOkay);
7990b57cec5SDimitry Andric     state = stateOkay;
8000b57cec5SDimitry Andric   }
8010b57cec5SDimitry Andric 
8020b57cec5SDimitry Andric   return state;
8030b57cec5SDimitry Andric }
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
8060b57cec5SDimitry Andric                                                 const MemRegion *MR,
8070b57cec5SDimitry Andric                                                 SVal strLength) {
8080b57cec5SDimitry Andric   assert(!strLength.isUndef() && "Attempt to set an undefined string length");
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric   MR = MR->StripCasts();
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric   switch (MR->getKind()) {
8130b57cec5SDimitry Andric   case MemRegion::StringRegionKind:
8140b57cec5SDimitry Andric     // FIXME: This can happen if we strcpy() into a string region. This is
8150b57cec5SDimitry Andric     // undefined [C99 6.4.5p6], but we should still warn about it.
8160b57cec5SDimitry Andric     return state;
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric   case MemRegion::SymbolicRegionKind:
8190b57cec5SDimitry Andric   case MemRegion::AllocaRegionKind:
8205ffd83dbSDimitry Andric   case MemRegion::NonParamVarRegionKind:
8215ffd83dbSDimitry Andric   case MemRegion::ParamVarRegionKind:
8220b57cec5SDimitry Andric   case MemRegion::FieldRegionKind:
8230b57cec5SDimitry Andric   case MemRegion::ObjCIvarRegionKind:
8240b57cec5SDimitry Andric     // These are the types we can currently track string lengths for.
8250b57cec5SDimitry Andric     break;
8260b57cec5SDimitry Andric 
8270b57cec5SDimitry Andric   case MemRegion::ElementRegionKind:
8280b57cec5SDimitry Andric     // FIXME: Handle element regions by upper-bounding the parent region's
8290b57cec5SDimitry Andric     // string length.
8300b57cec5SDimitry Andric     return state;
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric   default:
8330b57cec5SDimitry Andric     // Other regions (mostly non-data) can't have a reliable C string length.
8340b57cec5SDimitry Andric     // For now, just ignore the change.
8350b57cec5SDimitry Andric     // FIXME: These are rare but not impossible. We should output some kind of
8360b57cec5SDimitry Andric     // warning for things like strcpy((char[]){'a', 0}, "b");
8370b57cec5SDimitry Andric     return state;
8380b57cec5SDimitry Andric   }
8390b57cec5SDimitry Andric 
8400b57cec5SDimitry Andric   if (strLength.isUnknown())
8410b57cec5SDimitry Andric     return state->remove<CStringLength>(MR);
8420b57cec5SDimitry Andric 
8430b57cec5SDimitry Andric   return state->set<CStringLength>(MR, strLength);
8440b57cec5SDimitry Andric }
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
8470b57cec5SDimitry Andric                                                ProgramStateRef &state,
8480b57cec5SDimitry Andric                                                const Expr *Ex,
8490b57cec5SDimitry Andric                                                const MemRegion *MR,
8500b57cec5SDimitry Andric                                                bool hypothetical) {
8510b57cec5SDimitry Andric   if (!hypothetical) {
8520b57cec5SDimitry Andric     // If there's a recorded length, go ahead and return it.
8530b57cec5SDimitry Andric     const SVal *Recorded = state->get<CStringLength>(MR);
8540b57cec5SDimitry Andric     if (Recorded)
8550b57cec5SDimitry Andric       return *Recorded;
8560b57cec5SDimitry Andric   }
8570b57cec5SDimitry Andric 
8580b57cec5SDimitry Andric   // Otherwise, get a new symbol and update the state.
8590b57cec5SDimitry Andric   SValBuilder &svalBuilder = C.getSValBuilder();
8600b57cec5SDimitry Andric   QualType sizeTy = svalBuilder.getContext().getSizeType();
8610b57cec5SDimitry Andric   SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
8620b57cec5SDimitry Andric                                                     MR, Ex, sizeTy,
8630b57cec5SDimitry Andric                                                     C.getLocationContext(),
8640b57cec5SDimitry Andric                                                     C.blockCount());
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric   if (!hypothetical) {
867bdd1243dSDimitry Andric     if (std::optional<NonLoc> strLn = strLength.getAs<NonLoc>()) {
8680b57cec5SDimitry Andric       // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4
8690b57cec5SDimitry Andric       BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
8700b57cec5SDimitry Andric       const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
8710b57cec5SDimitry Andric       llvm::APSInt fourInt = APSIntType(maxValInt).getValue(4);
8720b57cec5SDimitry Andric       const llvm::APSInt *maxLengthInt = BVF.evalAPSInt(BO_Div, maxValInt,
8730b57cec5SDimitry Andric                                                         fourInt);
8740b57cec5SDimitry Andric       NonLoc maxLength = svalBuilder.makeIntVal(*maxLengthInt);
8750b57cec5SDimitry Andric       SVal evalLength = svalBuilder.evalBinOpNN(state, BO_LE, *strLn,
8760b57cec5SDimitry Andric                                                 maxLength, sizeTy);
8770b57cec5SDimitry Andric       state = state->assume(evalLength.castAs<DefinedOrUnknownSVal>(), true);
8780b57cec5SDimitry Andric     }
8790b57cec5SDimitry Andric     state = state->set<CStringLength>(MR, strLength);
8800b57cec5SDimitry Andric   }
8810b57cec5SDimitry Andric 
8820b57cec5SDimitry Andric   return strLength;
8830b57cec5SDimitry Andric }
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
8860b57cec5SDimitry Andric                                       const Expr *Ex, SVal Buf,
8870b57cec5SDimitry Andric                                       bool hypothetical) const {
8880b57cec5SDimitry Andric   const MemRegion *MR = Buf.getAsRegion();
8890b57cec5SDimitry Andric   if (!MR) {
8900b57cec5SDimitry Andric     // If we can't get a region, see if it's something we /know/ isn't a
8910b57cec5SDimitry Andric     // C string. In the context of locations, the only time we can issue such
8920b57cec5SDimitry Andric     // a warning is for labels.
893bdd1243dSDimitry Andric     if (std::optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) {
8940b57cec5SDimitry Andric       if (Filter.CheckCStringNotNullTerm) {
8950b57cec5SDimitry Andric         SmallString<120> buf;
8960b57cec5SDimitry Andric         llvm::raw_svector_ostream os(buf);
8970b57cec5SDimitry Andric         assert(CurrentFunctionDescription);
8980b57cec5SDimitry Andric         os << "Argument to " << CurrentFunctionDescription
8990b57cec5SDimitry Andric            << " is the address of the label '" << Label->getLabel()->getName()
9000b57cec5SDimitry Andric            << "', which is not a null-terminated string";
9010b57cec5SDimitry Andric 
9020b57cec5SDimitry Andric         emitNotCStringBug(C, state, Ex, os.str());
9030b57cec5SDimitry Andric       }
9040b57cec5SDimitry Andric       return UndefinedVal();
9050b57cec5SDimitry Andric     }
9060b57cec5SDimitry Andric 
9070b57cec5SDimitry Andric     // If it's not a region and not a label, give up.
9080b57cec5SDimitry Andric     return UnknownVal();
9090b57cec5SDimitry Andric   }
9100b57cec5SDimitry Andric 
9110b57cec5SDimitry Andric   // If we have a region, strip casts from it and see if we can figure out
9120b57cec5SDimitry Andric   // its length. For anything we can't figure out, just return UnknownVal.
9130b57cec5SDimitry Andric   MR = MR->StripCasts();
9140b57cec5SDimitry Andric 
9150b57cec5SDimitry Andric   switch (MR->getKind()) {
9160b57cec5SDimitry Andric   case MemRegion::StringRegionKind: {
9170b57cec5SDimitry Andric     // Modifying the contents of string regions is undefined [C99 6.4.5p6],
9180b57cec5SDimitry Andric     // so we can assume that the byte length is the correct C string length.
9190b57cec5SDimitry Andric     SValBuilder &svalBuilder = C.getSValBuilder();
9200b57cec5SDimitry Andric     QualType sizeTy = svalBuilder.getContext().getSizeType();
9210b57cec5SDimitry Andric     const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
922753f127fSDimitry Andric     return svalBuilder.makeIntVal(strLit->getLength(), sizeTy);
9230b57cec5SDimitry Andric   }
9240b57cec5SDimitry Andric   case MemRegion::SymbolicRegionKind:
9250b57cec5SDimitry Andric   case MemRegion::AllocaRegionKind:
9265ffd83dbSDimitry Andric   case MemRegion::NonParamVarRegionKind:
9275ffd83dbSDimitry Andric   case MemRegion::ParamVarRegionKind:
9280b57cec5SDimitry Andric   case MemRegion::FieldRegionKind:
9290b57cec5SDimitry Andric   case MemRegion::ObjCIvarRegionKind:
9300b57cec5SDimitry Andric     return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
9310b57cec5SDimitry Andric   case MemRegion::CompoundLiteralRegionKind:
9320b57cec5SDimitry Andric     // FIXME: Can we track this? Is it necessary?
9330b57cec5SDimitry Andric     return UnknownVal();
9340b57cec5SDimitry Andric   case MemRegion::ElementRegionKind:
9350b57cec5SDimitry Andric     // FIXME: How can we handle this? It's not good enough to subtract the
9360b57cec5SDimitry Andric     // offset from the base string length; consider "123\x00567" and &a[5].
9370b57cec5SDimitry Andric     return UnknownVal();
9380b57cec5SDimitry Andric   default:
9390b57cec5SDimitry Andric     // Other regions (mostly non-data) can't have a reliable C string length.
9400b57cec5SDimitry Andric     // In this case, an error is emitted and UndefinedVal is returned.
9410b57cec5SDimitry Andric     // The caller should always be prepared to handle this case.
9420b57cec5SDimitry Andric     if (Filter.CheckCStringNotNullTerm) {
9430b57cec5SDimitry Andric       SmallString<120> buf;
9440b57cec5SDimitry Andric       llvm::raw_svector_ostream os(buf);
9450b57cec5SDimitry Andric 
9460b57cec5SDimitry Andric       assert(CurrentFunctionDescription);
9470b57cec5SDimitry Andric       os << "Argument to " << CurrentFunctionDescription << " is ";
9480b57cec5SDimitry Andric 
9490b57cec5SDimitry Andric       if (SummarizeRegion(os, C.getASTContext(), MR))
9500b57cec5SDimitry Andric         os << ", which is not a null-terminated string";
9510b57cec5SDimitry Andric       else
9520b57cec5SDimitry Andric         os << "not a null-terminated string";
9530b57cec5SDimitry Andric 
9540b57cec5SDimitry Andric       emitNotCStringBug(C, state, Ex, os.str());
9550b57cec5SDimitry Andric     }
9560b57cec5SDimitry Andric     return UndefinedVal();
9570b57cec5SDimitry Andric   }
9580b57cec5SDimitry Andric }
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
9610b57cec5SDimitry Andric   ProgramStateRef &state, const Expr *expr, SVal val) const {
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric   // Get the memory region pointed to by the val.
9640b57cec5SDimitry Andric   const MemRegion *bufRegion = val.getAsRegion();
9650b57cec5SDimitry Andric   if (!bufRegion)
9660b57cec5SDimitry Andric     return nullptr;
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric   // Strip casts off the memory region.
9690b57cec5SDimitry Andric   bufRegion = bufRegion->StripCasts();
9700b57cec5SDimitry Andric 
9710b57cec5SDimitry Andric   // Cast the memory region to a string region.
9720b57cec5SDimitry Andric   const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
9730b57cec5SDimitry Andric   if (!strRegion)
9740b57cec5SDimitry Andric     return nullptr;
9750b57cec5SDimitry Andric 
9760b57cec5SDimitry Andric   // Return the actual string in the string region.
9770b57cec5SDimitry Andric   return strRegion->getStringLiteral();
9780b57cec5SDimitry Andric }
9790b57cec5SDimitry Andric 
980*06c3fb27SDimitry Andric bool CStringChecker::isFirstBufInBound(CheckerContext &C, ProgramStateRef State,
981*06c3fb27SDimitry Andric                                        SVal BufVal, QualType BufTy,
982*06c3fb27SDimitry Andric                                        SVal LengthVal, QualType LengthTy) {
9830b57cec5SDimitry Andric   // If we do not know that the buffer is long enough we return 'true'.
9840b57cec5SDimitry Andric   // Otherwise the parent region of this field region would also get
9850b57cec5SDimitry Andric   // invalidated, which would lead to warnings based on an unknown state.
9860b57cec5SDimitry Andric 
987*06c3fb27SDimitry Andric   if (LengthVal.isUnknown())
988*06c3fb27SDimitry Andric     return false;
989*06c3fb27SDimitry Andric 
9900b57cec5SDimitry Andric   // Originally copied from CheckBufferAccess and CheckLocation.
991*06c3fb27SDimitry Andric   SValBuilder &SB = C.getSValBuilder();
992*06c3fb27SDimitry Andric   ASTContext &Ctx = C.getASTContext();
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric   QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
9950b57cec5SDimitry Andric 
996bdd1243dSDimitry Andric   std::optional<NonLoc> Length = LengthVal.getAs<NonLoc>();
9970b57cec5SDimitry Andric   if (!Length)
9980b57cec5SDimitry Andric     return true; // cf top comment.
9990b57cec5SDimitry Andric 
10000b57cec5SDimitry Andric   // Compute the offset of the last element to be accessed: size-1.
1001*06c3fb27SDimitry Andric   NonLoc One = SB.makeIntVal(1, LengthTy).castAs<NonLoc>();
1002*06c3fb27SDimitry Andric   SVal Offset = SB.evalBinOpNN(State, BO_Sub, *Length, One, LengthTy);
10030b57cec5SDimitry Andric   if (Offset.isUnknown())
10040b57cec5SDimitry Andric     return true; // cf top comment
10050b57cec5SDimitry Andric   NonLoc LastOffset = Offset.castAs<NonLoc>();
10060b57cec5SDimitry Andric 
10070b57cec5SDimitry Andric   // Check that the first buffer is sufficiently long.
1008*06c3fb27SDimitry Andric   SVal BufStart = SB.evalCast(BufVal, PtrTy, BufTy);
1009bdd1243dSDimitry Andric   std::optional<Loc> BufLoc = BufStart.getAs<Loc>();
10100b57cec5SDimitry Andric   if (!BufLoc)
10110b57cec5SDimitry Andric     return true; // cf top comment.
10120b57cec5SDimitry Andric 
1013*06c3fb27SDimitry Andric   SVal BufEnd = SB.evalBinOpLN(State, BO_Add, *BufLoc, LastOffset, PtrTy);
10140b57cec5SDimitry Andric 
10150b57cec5SDimitry Andric   // Check for out of bound array element access.
10160b57cec5SDimitry Andric   const MemRegion *R = BufEnd.getAsRegion();
10170b57cec5SDimitry Andric   if (!R)
10180b57cec5SDimitry Andric     return true; // cf top comment.
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric   const ElementRegion *ER = dyn_cast<ElementRegion>(R);
10210b57cec5SDimitry Andric   if (!ER)
10220b57cec5SDimitry Andric     return true; // cf top comment.
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric   // FIXME: Does this crash when a non-standard definition
10250b57cec5SDimitry Andric   // of a library function is encountered?
10260b57cec5SDimitry Andric   assert(ER->getValueType() == C.getASTContext().CharTy &&
1027*06c3fb27SDimitry Andric          "isFirstBufInBound should only be called with char* ElementRegions");
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric   // Get the size of the array.
10300b57cec5SDimitry Andric   const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
1031*06c3fb27SDimitry Andric   DefinedOrUnknownSVal SizeDV = getDynamicExtent(State, superReg, SB);
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric   // Get the index of the accessed element.
10340b57cec5SDimitry Andric   DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>();
10350b57cec5SDimitry Andric 
1036*06c3fb27SDimitry Andric   ProgramStateRef StInBound = State->assumeInBound(Idx, SizeDV, true);
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric   return static_cast<bool>(StInBound);
10390b57cec5SDimitry Andric }
10400b57cec5SDimitry Andric 
1041*06c3fb27SDimitry Andric ProgramStateRef CStringChecker::invalidateDestinationBufferBySize(
1042*06c3fb27SDimitry Andric     CheckerContext &C, ProgramStateRef S, const Expr *BufE, SVal BufV,
1043*06c3fb27SDimitry Andric     SVal SizeV, QualType SizeTy) {
1044*06c3fb27SDimitry Andric   auto InvalidationTraitOperations =
1045*06c3fb27SDimitry Andric       [&C, S, BufTy = BufE->getType(), BufV, SizeV,
1046*06c3fb27SDimitry Andric        SizeTy](RegionAndSymbolInvalidationTraits &ITraits, const MemRegion *R) {
1047*06c3fb27SDimitry Andric         // If destination buffer is a field region and access is in bound, do
1048*06c3fb27SDimitry Andric         // not invalidate its super region.
1049*06c3fb27SDimitry Andric         if (MemRegion::FieldRegionKind == R->getKind() &&
1050*06c3fb27SDimitry Andric             isFirstBufInBound(C, S, BufV, BufTy, SizeV, SizeTy)) {
1051*06c3fb27SDimitry Andric           ITraits.setTrait(
1052*06c3fb27SDimitry Andric               R,
1053*06c3fb27SDimitry Andric               RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
1054*06c3fb27SDimitry Andric         }
1055*06c3fb27SDimitry Andric         return false;
1056*06c3fb27SDimitry Andric       };
1057*06c3fb27SDimitry Andric 
1058*06c3fb27SDimitry Andric   return invalidateBufferAux(C, S, BufE, BufV, InvalidationTraitOperations);
1059*06c3fb27SDimitry Andric }
1060*06c3fb27SDimitry Andric 
1061*06c3fb27SDimitry Andric ProgramStateRef
1062*06c3fb27SDimitry Andric CStringChecker::invalidateDestinationBufferAlwaysEscapeSuperRegion(
1063*06c3fb27SDimitry Andric     CheckerContext &C, ProgramStateRef S, const Expr *BufE, SVal BufV) {
1064*06c3fb27SDimitry Andric   auto InvalidationTraitOperations = [](RegionAndSymbolInvalidationTraits &,
1065*06c3fb27SDimitry Andric                                         const MemRegion *R) {
1066*06c3fb27SDimitry Andric     return isa<FieldRegion>(R);
1067*06c3fb27SDimitry Andric   };
1068*06c3fb27SDimitry Andric 
1069*06c3fb27SDimitry Andric   return invalidateBufferAux(C, S, BufE, BufV, InvalidationTraitOperations);
1070*06c3fb27SDimitry Andric }
1071*06c3fb27SDimitry Andric 
1072*06c3fb27SDimitry Andric ProgramStateRef CStringChecker::invalidateDestinationBufferNeverOverflows(
1073*06c3fb27SDimitry Andric     CheckerContext &C, ProgramStateRef S, const Expr *BufE, SVal BufV) {
1074*06c3fb27SDimitry Andric   auto InvalidationTraitOperations =
1075*06c3fb27SDimitry Andric       [](RegionAndSymbolInvalidationTraits &ITraits, const MemRegion *R) {
1076*06c3fb27SDimitry Andric         if (MemRegion::FieldRegionKind == R->getKind())
1077*06c3fb27SDimitry Andric           ITraits.setTrait(
1078*06c3fb27SDimitry Andric               R,
1079*06c3fb27SDimitry Andric               RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
1080*06c3fb27SDimitry Andric         return false;
1081*06c3fb27SDimitry Andric       };
1082*06c3fb27SDimitry Andric 
1083*06c3fb27SDimitry Andric   return invalidateBufferAux(C, S, BufE, BufV, InvalidationTraitOperations);
1084*06c3fb27SDimitry Andric }
1085*06c3fb27SDimitry Andric 
1086*06c3fb27SDimitry Andric ProgramStateRef CStringChecker::invalidateSourceBuffer(CheckerContext &C,
1087*06c3fb27SDimitry Andric                                                        ProgramStateRef S,
1088*06c3fb27SDimitry Andric                                                        const Expr *BufE,
1089*06c3fb27SDimitry Andric                                                        SVal BufV) {
1090*06c3fb27SDimitry Andric   auto InvalidationTraitOperations =
1091*06c3fb27SDimitry Andric       [](RegionAndSymbolInvalidationTraits &ITraits, const MemRegion *R) {
1092*06c3fb27SDimitry Andric         ITraits.setTrait(
1093*06c3fb27SDimitry Andric             R->getBaseRegion(),
1094*06c3fb27SDimitry Andric             RegionAndSymbolInvalidationTraits::TK_PreserveContents);
1095*06c3fb27SDimitry Andric         ITraits.setTrait(R,
1096*06c3fb27SDimitry Andric                          RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
1097*06c3fb27SDimitry Andric         return true;
1098*06c3fb27SDimitry Andric       };
1099*06c3fb27SDimitry Andric 
1100*06c3fb27SDimitry Andric   return invalidateBufferAux(C, S, BufE, BufV, InvalidationTraitOperations);
1101*06c3fb27SDimitry Andric }
1102*06c3fb27SDimitry Andric 
1103*06c3fb27SDimitry Andric ProgramStateRef CStringChecker::invalidateBufferAux(
1104*06c3fb27SDimitry Andric     CheckerContext &C, ProgramStateRef State, const Expr *E, SVal V,
1105*06c3fb27SDimitry Andric     llvm::function_ref<bool(RegionAndSymbolInvalidationTraits &,
1106*06c3fb27SDimitry Andric                             const MemRegion *)>
1107*06c3fb27SDimitry Andric         InvalidationTraitOperations) {
1108bdd1243dSDimitry Andric   std::optional<Loc> L = V.getAs<Loc>();
11090b57cec5SDimitry Andric   if (!L)
1110*06c3fb27SDimitry Andric     return State;
11110b57cec5SDimitry Andric 
11120b57cec5SDimitry Andric   // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
11130b57cec5SDimitry Andric   // some assumptions about the value that CFRefCount can't. Even so, it should
11140b57cec5SDimitry Andric   // probably be refactored.
1115bdd1243dSDimitry Andric   if (std::optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) {
11160b57cec5SDimitry Andric     const MemRegion *R = MR->getRegion()->StripCasts();
11170b57cec5SDimitry Andric 
11180b57cec5SDimitry Andric     // Are we dealing with an ElementRegion?  If so, we should be invalidating
11190b57cec5SDimitry Andric     // the super-region.
11200b57cec5SDimitry Andric     if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
11210b57cec5SDimitry Andric       R = ER->getSuperRegion();
11220b57cec5SDimitry Andric       // FIXME: What about layers of ElementRegions?
11230b57cec5SDimitry Andric     }
11240b57cec5SDimitry Andric 
11250b57cec5SDimitry Andric     // Invalidate this region.
11260b57cec5SDimitry Andric     const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
11270b57cec5SDimitry Andric     RegionAndSymbolInvalidationTraits ITraits;
1128*06c3fb27SDimitry Andric     bool CausesPointerEscape = InvalidationTraitOperations(ITraits, R);
11290b57cec5SDimitry Andric 
1130*06c3fb27SDimitry Andric     return State->invalidateRegions(R, E, C.blockCount(), LCtx,
11310b57cec5SDimitry Andric                                     CausesPointerEscape, nullptr, nullptr,
11320b57cec5SDimitry Andric                                     &ITraits);
11330b57cec5SDimitry Andric   }
11340b57cec5SDimitry Andric 
11350b57cec5SDimitry Andric   // If we have a non-region value by chance, just remove the binding.
11360b57cec5SDimitry Andric   // FIXME: is this necessary or correct? This handles the non-Region
11370b57cec5SDimitry Andric   //  cases.  Is it ever valid to store to these?
1138*06c3fb27SDimitry Andric   return State->killBinding(*L);
11390b57cec5SDimitry Andric }
11400b57cec5SDimitry Andric 
11410b57cec5SDimitry Andric bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
11420b57cec5SDimitry Andric                                      const MemRegion *MR) {
11430b57cec5SDimitry Andric   switch (MR->getKind()) {
11440b57cec5SDimitry Andric   case MemRegion::FunctionCodeRegionKind: {
1145480093f4SDimitry Andric     if (const auto *FD = cast<FunctionCodeRegion>(MR)->getDecl())
11460b57cec5SDimitry Andric       os << "the address of the function '" << *FD << '\'';
11470b57cec5SDimitry Andric     else
11480b57cec5SDimitry Andric       os << "the address of a function";
11490b57cec5SDimitry Andric     return true;
11500b57cec5SDimitry Andric   }
11510b57cec5SDimitry Andric   case MemRegion::BlockCodeRegionKind:
11520b57cec5SDimitry Andric     os << "block text";
11530b57cec5SDimitry Andric     return true;
11540b57cec5SDimitry Andric   case MemRegion::BlockDataRegionKind:
11550b57cec5SDimitry Andric     os << "a block";
11560b57cec5SDimitry Andric     return true;
11570b57cec5SDimitry Andric   case MemRegion::CXXThisRegionKind:
11580b57cec5SDimitry Andric   case MemRegion::CXXTempObjectRegionKind:
1159480093f4SDimitry Andric     os << "a C++ temp object of type "
116081ad6265SDimitry Andric        << cast<TypedValueRegion>(MR)->getValueType();
11610b57cec5SDimitry Andric     return true;
11625ffd83dbSDimitry Andric   case MemRegion::NonParamVarRegionKind:
116381ad6265SDimitry Andric     os << "a variable of type" << cast<TypedValueRegion>(MR)->getValueType();
11640b57cec5SDimitry Andric     return true;
11655ffd83dbSDimitry Andric   case MemRegion::ParamVarRegionKind:
116681ad6265SDimitry Andric     os << "a parameter of type" << cast<TypedValueRegion>(MR)->getValueType();
11675ffd83dbSDimitry Andric     return true;
11680b57cec5SDimitry Andric   case MemRegion::FieldRegionKind:
116981ad6265SDimitry Andric     os << "a field of type " << cast<TypedValueRegion>(MR)->getValueType();
11700b57cec5SDimitry Andric     return true;
11710b57cec5SDimitry Andric   case MemRegion::ObjCIvarRegionKind:
1172480093f4SDimitry Andric     os << "an instance variable of type "
117381ad6265SDimitry Andric        << cast<TypedValueRegion>(MR)->getValueType();
11740b57cec5SDimitry Andric     return true;
11750b57cec5SDimitry Andric   default:
11760b57cec5SDimitry Andric     return false;
11770b57cec5SDimitry Andric   }
11780b57cec5SDimitry Andric }
11790b57cec5SDimitry Andric 
11800b57cec5SDimitry Andric bool CStringChecker::memsetAux(const Expr *DstBuffer, SVal CharVal,
11810b57cec5SDimitry Andric                                const Expr *Size, CheckerContext &C,
11820b57cec5SDimitry Andric                                ProgramStateRef &State) {
11830b57cec5SDimitry Andric   SVal MemVal = C.getSVal(DstBuffer);
11840b57cec5SDimitry Andric   SVal SizeVal = C.getSVal(Size);
11850b57cec5SDimitry Andric   const MemRegion *MR = MemVal.getAsRegion();
11860b57cec5SDimitry Andric   if (!MR)
11870b57cec5SDimitry Andric     return false;
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric   // We're about to model memset by producing a "default binding" in the Store.
11900b57cec5SDimitry Andric   // Our current implementation - RegionStore - doesn't support default bindings
11910b57cec5SDimitry Andric   // that don't cover the whole base region. So we should first get the offset
11920b57cec5SDimitry Andric   // and the base region to figure out whether the offset of buffer is 0.
11930b57cec5SDimitry Andric   RegionOffset Offset = MR->getAsOffset();
11940b57cec5SDimitry Andric   const MemRegion *BR = Offset.getRegion();
11950b57cec5SDimitry Andric 
1196bdd1243dSDimitry Andric   std::optional<NonLoc> SizeNL = SizeVal.getAs<NonLoc>();
11970b57cec5SDimitry Andric   if (!SizeNL)
11980b57cec5SDimitry Andric     return false;
11990b57cec5SDimitry Andric 
12000b57cec5SDimitry Andric   SValBuilder &svalBuilder = C.getSValBuilder();
12010b57cec5SDimitry Andric   ASTContext &Ctx = C.getASTContext();
12020b57cec5SDimitry Andric 
12030b57cec5SDimitry Andric   // void *memset(void *dest, int ch, size_t count);
12040b57cec5SDimitry Andric   // For now we can only handle the case of offset is 0 and concrete char value.
12050b57cec5SDimitry Andric   if (Offset.isValid() && !Offset.hasSymbolicOffset() &&
12060b57cec5SDimitry Andric       Offset.getOffset() == 0) {
12075ffd83dbSDimitry Andric     // Get the base region's size.
1208fe6060f1SDimitry Andric     DefinedOrUnknownSVal SizeDV = getDynamicExtent(State, BR, svalBuilder);
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric     ProgramStateRef StateWholeReg, StateNotWholeReg;
12110b57cec5SDimitry Andric     std::tie(StateWholeReg, StateNotWholeReg) =
12125ffd83dbSDimitry Andric         State->assume(svalBuilder.evalEQ(State, SizeDV, *SizeNL));
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric     // With the semantic of 'memset()', we should convert the CharVal to
12150b57cec5SDimitry Andric     // unsigned char.
12160b57cec5SDimitry Andric     CharVal = svalBuilder.evalCast(CharVal, Ctx.UnsignedCharTy, Ctx.IntTy);
12170b57cec5SDimitry Andric 
12180b57cec5SDimitry Andric     ProgramStateRef StateNullChar, StateNonNullChar;
12190b57cec5SDimitry Andric     std::tie(StateNullChar, StateNonNullChar) =
12200b57cec5SDimitry Andric         assumeZero(C, State, CharVal, Ctx.UnsignedCharTy);
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric     if (StateWholeReg && !StateNotWholeReg && StateNullChar &&
12230b57cec5SDimitry Andric         !StateNonNullChar) {
12240b57cec5SDimitry Andric       // If the 'memset()' acts on the whole region of destination buffer and
12250b57cec5SDimitry Andric       // the value of the second argument of 'memset()' is zero, bind the second
12260b57cec5SDimitry Andric       // argument's value to the destination buffer with 'default binding'.
12270b57cec5SDimitry Andric       // FIXME: Since there is no perfect way to bind the non-zero character, we
12280b57cec5SDimitry Andric       // can only deal with zero value here. In the future, we need to deal with
12290b57cec5SDimitry Andric       // the binding of non-zero value in the case of whole region.
12300b57cec5SDimitry Andric       State = State->bindDefaultZero(svalBuilder.makeLoc(BR),
12310b57cec5SDimitry Andric                                      C.getLocationContext());
12320b57cec5SDimitry Andric     } else {
12330b57cec5SDimitry Andric       // If the destination buffer's extent is not equal to the value of
12340b57cec5SDimitry Andric       // third argument, just invalidate buffer.
1235*06c3fb27SDimitry Andric       State = invalidateDestinationBufferBySize(C, State, DstBuffer, MemVal,
1236*06c3fb27SDimitry Andric                                                 SizeVal, Size->getType());
12370b57cec5SDimitry Andric     }
12380b57cec5SDimitry Andric 
12390b57cec5SDimitry Andric     if (StateNullChar && !StateNonNullChar) {
12400b57cec5SDimitry Andric       // If the value of the second argument of 'memset()' is zero, set the
12410b57cec5SDimitry Andric       // string length of destination buffer to 0 directly.
12420b57cec5SDimitry Andric       State = setCStringLength(State, MR,
12430b57cec5SDimitry Andric                                svalBuilder.makeZeroVal(Ctx.getSizeType()));
12440b57cec5SDimitry Andric     } else if (!StateNullChar && StateNonNullChar) {
12450b57cec5SDimitry Andric       SVal NewStrLen = svalBuilder.getMetadataSymbolVal(
12460b57cec5SDimitry Andric           CStringChecker::getTag(), MR, DstBuffer, Ctx.getSizeType(),
12470b57cec5SDimitry Andric           C.getLocationContext(), C.blockCount());
12480b57cec5SDimitry Andric 
12490b57cec5SDimitry Andric       // If the value of second argument is not zero, then the string length
12500b57cec5SDimitry Andric       // is at least the size argument.
12510b57cec5SDimitry Andric       SVal NewStrLenGESize = svalBuilder.evalBinOp(
12520b57cec5SDimitry Andric           State, BO_GE, NewStrLen, SizeVal, svalBuilder.getConditionType());
12530b57cec5SDimitry Andric 
12540b57cec5SDimitry Andric       State = setCStringLength(
12550b57cec5SDimitry Andric           State->assume(NewStrLenGESize.castAs<DefinedOrUnknownSVal>(), true),
12560b57cec5SDimitry Andric           MR, NewStrLen);
12570b57cec5SDimitry Andric     }
12580b57cec5SDimitry Andric   } else {
12590b57cec5SDimitry Andric     // If the offset is not zero and char value is not concrete, we can do
12600b57cec5SDimitry Andric     // nothing but invalidate the buffer.
1261*06c3fb27SDimitry Andric     State = invalidateDestinationBufferBySize(C, State, DstBuffer, MemVal,
1262*06c3fb27SDimitry Andric                                               SizeVal, Size->getType());
12630b57cec5SDimitry Andric   }
12640b57cec5SDimitry Andric   return true;
12650b57cec5SDimitry Andric }
12660b57cec5SDimitry Andric 
12670b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12680b57cec5SDimitry Andric // evaluation of individual function calls.
12690b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12700b57cec5SDimitry Andric 
12715ffd83dbSDimitry Andric void CStringChecker::evalCopyCommon(CheckerContext &C, const CallExpr *CE,
12725ffd83dbSDimitry Andric                                     ProgramStateRef state, SizeArgExpr Size,
12735ffd83dbSDimitry Andric                                     DestinationArgExpr Dest,
12745ffd83dbSDimitry Andric                                     SourceArgExpr Source, bool Restricted,
1275bdd1243dSDimitry Andric                                     bool IsMempcpy, CharKind CK) const {
12760b57cec5SDimitry Andric   CurrentFunctionDescription = "memory copy function";
12770b57cec5SDimitry Andric 
12780b57cec5SDimitry Andric   // See if the size argument is zero.
12790b57cec5SDimitry Andric   const LocationContext *LCtx = C.getLocationContext();
12805ffd83dbSDimitry Andric   SVal sizeVal = state->getSVal(Size.Expression, LCtx);
12815ffd83dbSDimitry Andric   QualType sizeTy = Size.Expression->getType();
12820b57cec5SDimitry Andric 
12830b57cec5SDimitry Andric   ProgramStateRef stateZeroSize, stateNonZeroSize;
12840b57cec5SDimitry Andric   std::tie(stateZeroSize, stateNonZeroSize) =
12850b57cec5SDimitry Andric       assumeZero(C, state, sizeVal, sizeTy);
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric   // Get the value of the Dest.
12885ffd83dbSDimitry Andric   SVal destVal = state->getSVal(Dest.Expression, LCtx);
12890b57cec5SDimitry Andric 
12900b57cec5SDimitry Andric   // If the size is zero, there won't be any actual memory access, so
12910b57cec5SDimitry Andric   // just bind the return value to the destination buffer and return.
12920b57cec5SDimitry Andric   if (stateZeroSize && !stateNonZeroSize) {
12930b57cec5SDimitry Andric     stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
12940b57cec5SDimitry Andric     C.addTransition(stateZeroSize);
12950b57cec5SDimitry Andric     return;
12960b57cec5SDimitry Andric   }
12970b57cec5SDimitry Andric 
12980b57cec5SDimitry Andric   // If the size can be nonzero, we have to check the other arguments.
12990b57cec5SDimitry Andric   if (stateNonZeroSize) {
13000b57cec5SDimitry Andric     state = stateNonZeroSize;
13010b57cec5SDimitry Andric 
13020b57cec5SDimitry Andric     // Ensure the destination is not null. If it is NULL there will be a
13030b57cec5SDimitry Andric     // NULL pointer dereference.
13045ffd83dbSDimitry Andric     state = checkNonNull(C, state, Dest, destVal);
13050b57cec5SDimitry Andric     if (!state)
13060b57cec5SDimitry Andric       return;
13070b57cec5SDimitry Andric 
13080b57cec5SDimitry Andric     // Get the value of the Src.
13095ffd83dbSDimitry Andric     SVal srcVal = state->getSVal(Source.Expression, LCtx);
13100b57cec5SDimitry Andric 
13110b57cec5SDimitry Andric     // Ensure the source is not null. If it is NULL there will be a
13120b57cec5SDimitry Andric     // NULL pointer dereference.
13135ffd83dbSDimitry Andric     state = checkNonNull(C, state, Source, srcVal);
13140b57cec5SDimitry Andric     if (!state)
13150b57cec5SDimitry Andric       return;
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric     // Ensure the accesses are valid and that the buffers do not overlap.
1318bdd1243dSDimitry Andric     state = CheckBufferAccess(C, state, Dest, Size, AccessKind::write, CK);
1319bdd1243dSDimitry Andric     state = CheckBufferAccess(C, state, Source, Size, AccessKind::read, CK);
13205ffd83dbSDimitry Andric 
13210b57cec5SDimitry Andric     if (Restricted)
1322bdd1243dSDimitry Andric       state = CheckOverlap(C, state, Size, Dest, Source, CK);
13230b57cec5SDimitry Andric 
13240b57cec5SDimitry Andric     if (!state)
13250b57cec5SDimitry Andric       return;
13260b57cec5SDimitry Andric 
13270b57cec5SDimitry Andric     // If this is mempcpy, get the byte after the last byte copied and
13280b57cec5SDimitry Andric     // bind the expr.
13290b57cec5SDimitry Andric     if (IsMempcpy) {
13300b57cec5SDimitry Andric       // Get the byte after the last byte copied.
13310b57cec5SDimitry Andric       SValBuilder &SvalBuilder = C.getSValBuilder();
13320b57cec5SDimitry Andric       ASTContext &Ctx = SvalBuilder.getContext();
1333bdd1243dSDimitry Andric       QualType CharPtrTy = getCharPtrType(Ctx, CK);
13340b57cec5SDimitry Andric       SVal DestRegCharVal =
13355ffd83dbSDimitry Andric           SvalBuilder.evalCast(destVal, CharPtrTy, Dest.Expression->getType());
13360b57cec5SDimitry Andric       SVal lastElement = C.getSValBuilder().evalBinOp(
13375ffd83dbSDimitry Andric           state, BO_Add, DestRegCharVal, sizeVal, Dest.Expression->getType());
13380b57cec5SDimitry Andric       // If we don't know how much we copied, we can at least
13390b57cec5SDimitry Andric       // conjure a return value for later.
13400b57cec5SDimitry Andric       if (lastElement.isUnknown())
13410b57cec5SDimitry Andric         lastElement = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
13420b57cec5SDimitry Andric                                                           C.blockCount());
13430b57cec5SDimitry Andric 
13440b57cec5SDimitry Andric       // The byte after the last byte copied is the return value.
13450b57cec5SDimitry Andric       state = state->BindExpr(CE, LCtx, lastElement);
13460b57cec5SDimitry Andric     } else {
13470b57cec5SDimitry Andric       // All other copies return the destination buffer.
13480b57cec5SDimitry Andric       // (Well, bcopy() has a void return type, but this won't hurt.)
13490b57cec5SDimitry Andric       state = state->BindExpr(CE, LCtx, destVal);
13500b57cec5SDimitry Andric     }
13510b57cec5SDimitry Andric 
13520b57cec5SDimitry Andric     // Invalidate the destination (regular invalidation without pointer-escaping
13530b57cec5SDimitry Andric     // the address of the top-level region).
13540b57cec5SDimitry Andric     // FIXME: Even if we can't perfectly model the copy, we should see if we
13550b57cec5SDimitry Andric     // can use LazyCompoundVals to copy the source values into the destination.
13560b57cec5SDimitry Andric     // This would probably remove any existing bindings past the end of the
13570b57cec5SDimitry Andric     // copied region, but that's still an improvement over blank invalidation.
1358*06c3fb27SDimitry Andric     state = invalidateDestinationBufferBySize(
1359*06c3fb27SDimitry Andric         C, state, Dest.Expression, C.getSVal(Dest.Expression), sizeVal,
1360*06c3fb27SDimitry Andric         Size.Expression->getType());
13610b57cec5SDimitry Andric 
13620b57cec5SDimitry Andric     // Invalidate the source (const-invalidation without const-pointer-escaping
13630b57cec5SDimitry Andric     // the address of the top-level region).
1364*06c3fb27SDimitry Andric     state = invalidateSourceBuffer(C, state, Source.Expression,
1365*06c3fb27SDimitry Andric                                    C.getSVal(Source.Expression));
13660b57cec5SDimitry Andric 
13670b57cec5SDimitry Andric     C.addTransition(state);
13680b57cec5SDimitry Andric   }
13690b57cec5SDimitry Andric }
13700b57cec5SDimitry Andric 
1371972a253aSDimitry Andric void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE,
1372bdd1243dSDimitry Andric                                 CharKind CK) const {
13730b57cec5SDimitry Andric   // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
13740b57cec5SDimitry Andric   // The return value is the address of the destination buffer.
1375*06c3fb27SDimitry Andric   DestinationArgExpr Dest = {{CE->getArg(0), 0}};
1376*06c3fb27SDimitry Andric   SourceArgExpr Src = {{CE->getArg(1), 1}};
1377*06c3fb27SDimitry Andric   SizeArgExpr Size = {{CE->getArg(2), 2}};
13780b57cec5SDimitry Andric 
13795ffd83dbSDimitry Andric   ProgramStateRef State = C.getState();
13805ffd83dbSDimitry Andric 
13815ffd83dbSDimitry Andric   constexpr bool IsRestricted = true;
13825ffd83dbSDimitry Andric   constexpr bool IsMempcpy = false;
1383bdd1243dSDimitry Andric   evalCopyCommon(C, CE, State, Size, Dest, Src, IsRestricted, IsMempcpy, CK);
13840b57cec5SDimitry Andric }
13850b57cec5SDimitry Andric 
1386bdd1243dSDimitry Andric void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE,
1387bdd1243dSDimitry Andric                                  CharKind CK) const {
13880b57cec5SDimitry Andric   // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
13890b57cec5SDimitry Andric   // The return value is a pointer to the byte following the last written byte.
1390*06c3fb27SDimitry Andric   DestinationArgExpr Dest = {{CE->getArg(0), 0}};
1391*06c3fb27SDimitry Andric   SourceArgExpr Src = {{CE->getArg(1), 1}};
1392*06c3fb27SDimitry Andric   SizeArgExpr Size = {{CE->getArg(2), 2}};
13930b57cec5SDimitry Andric 
13945ffd83dbSDimitry Andric   constexpr bool IsRestricted = true;
13955ffd83dbSDimitry Andric   constexpr bool IsMempcpy = true;
1396972a253aSDimitry Andric   evalCopyCommon(C, CE, C.getState(), Size, Dest, Src, IsRestricted, IsMempcpy,
1397bdd1243dSDimitry Andric                  CK);
13980b57cec5SDimitry Andric }
13990b57cec5SDimitry Andric 
1400bdd1243dSDimitry Andric void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE,
1401bdd1243dSDimitry Andric                                  CharKind CK) const {
14020b57cec5SDimitry Andric   // void *memmove(void *dst, const void *src, size_t n);
14030b57cec5SDimitry Andric   // The return value is the address of the destination buffer.
1404*06c3fb27SDimitry Andric   DestinationArgExpr Dest = {{CE->getArg(0), 0}};
1405*06c3fb27SDimitry Andric   SourceArgExpr Src = {{CE->getArg(1), 1}};
1406*06c3fb27SDimitry Andric   SizeArgExpr Size = {{CE->getArg(2), 2}};
14070b57cec5SDimitry Andric 
14085ffd83dbSDimitry Andric   constexpr bool IsRestricted = false;
14095ffd83dbSDimitry Andric   constexpr bool IsMempcpy = false;
1410972a253aSDimitry Andric   evalCopyCommon(C, CE, C.getState(), Size, Dest, Src, IsRestricted, IsMempcpy,
1411bdd1243dSDimitry Andric                  CK);
14120b57cec5SDimitry Andric }
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
14150b57cec5SDimitry Andric   // void bcopy(const void *src, void *dst, size_t n);
1416*06c3fb27SDimitry Andric   SourceArgExpr Src{{CE->getArg(0), 0}};
1417*06c3fb27SDimitry Andric   DestinationArgExpr Dest = {{CE->getArg(1), 1}};
1418*06c3fb27SDimitry Andric   SizeArgExpr Size = {{CE->getArg(2), 2}};
14195ffd83dbSDimitry Andric 
14205ffd83dbSDimitry Andric   constexpr bool IsRestricted = false;
14215ffd83dbSDimitry Andric   constexpr bool IsMempcpy = false;
1422972a253aSDimitry Andric   evalCopyCommon(C, CE, C.getState(), Size, Dest, Src, IsRestricted, IsMempcpy,
1423bdd1243dSDimitry Andric                  CharKind::Regular);
14240b57cec5SDimitry Andric }
14250b57cec5SDimitry Andric 
1426bdd1243dSDimitry Andric void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE,
1427bdd1243dSDimitry Andric                                 CharKind CK) const {
14280b57cec5SDimitry Andric   // int memcmp(const void *s1, const void *s2, size_t n);
14290b57cec5SDimitry Andric   CurrentFunctionDescription = "memory comparison function";
14300b57cec5SDimitry Andric 
14315ffd83dbSDimitry Andric   AnyArgExpr Left = {CE->getArg(0), 0};
14325ffd83dbSDimitry Andric   AnyArgExpr Right = {CE->getArg(1), 1};
1433*06c3fb27SDimitry Andric   SizeArgExpr Size = {{CE->getArg(2), 2}};
14340b57cec5SDimitry Andric 
14355ffd83dbSDimitry Andric   ProgramStateRef State = C.getState();
14365ffd83dbSDimitry Andric   SValBuilder &Builder = C.getSValBuilder();
14375ffd83dbSDimitry Andric   const LocationContext *LCtx = C.getLocationContext();
14380b57cec5SDimitry Andric 
14390b57cec5SDimitry Andric   // See if the size argument is zero.
14405ffd83dbSDimitry Andric   SVal sizeVal = State->getSVal(Size.Expression, LCtx);
14415ffd83dbSDimitry Andric   QualType sizeTy = Size.Expression->getType();
14420b57cec5SDimitry Andric 
14430b57cec5SDimitry Andric   ProgramStateRef stateZeroSize, stateNonZeroSize;
14440b57cec5SDimitry Andric   std::tie(stateZeroSize, stateNonZeroSize) =
14455ffd83dbSDimitry Andric       assumeZero(C, State, sizeVal, sizeTy);
14460b57cec5SDimitry Andric 
14470b57cec5SDimitry Andric   // If the size can be zero, the result will be 0 in that case, and we don't
14480b57cec5SDimitry Andric   // have to check either of the buffers.
14490b57cec5SDimitry Andric   if (stateZeroSize) {
14505ffd83dbSDimitry Andric     State = stateZeroSize;
14515ffd83dbSDimitry Andric     State = State->BindExpr(CE, LCtx, Builder.makeZeroVal(CE->getType()));
14525ffd83dbSDimitry Andric     C.addTransition(State);
14530b57cec5SDimitry Andric   }
14540b57cec5SDimitry Andric 
14550b57cec5SDimitry Andric   // If the size can be nonzero, we have to check the other arguments.
14560b57cec5SDimitry Andric   if (stateNonZeroSize) {
14575ffd83dbSDimitry Andric     State = stateNonZeroSize;
14580b57cec5SDimitry Andric     // If we know the two buffers are the same, we know the result is 0.
14590b57cec5SDimitry Andric     // First, get the two buffers' addresses. Another checker will have already
14600b57cec5SDimitry Andric     // made sure they're not undefined.
14610b57cec5SDimitry Andric     DefinedOrUnknownSVal LV =
14625ffd83dbSDimitry Andric         State->getSVal(Left.Expression, LCtx).castAs<DefinedOrUnknownSVal>();
14630b57cec5SDimitry Andric     DefinedOrUnknownSVal RV =
14645ffd83dbSDimitry Andric         State->getSVal(Right.Expression, LCtx).castAs<DefinedOrUnknownSVal>();
14650b57cec5SDimitry Andric 
14660b57cec5SDimitry Andric     // See if they are the same.
14675ffd83dbSDimitry Andric     ProgramStateRef SameBuffer, NotSameBuffer;
14685ffd83dbSDimitry Andric     std::tie(SameBuffer, NotSameBuffer) =
14695ffd83dbSDimitry Andric         State->assume(Builder.evalEQ(State, LV, RV));
14700b57cec5SDimitry Andric 
1471480093f4SDimitry Andric     // If the two arguments are the same buffer, we know the result is 0,
14720b57cec5SDimitry Andric     // and we only need to check one size.
14735ffd83dbSDimitry Andric     if (SameBuffer && !NotSameBuffer) {
14745ffd83dbSDimitry Andric       State = SameBuffer;
14755ffd83dbSDimitry Andric       State = CheckBufferAccess(C, State, Left, Size, AccessKind::read);
14765ffd83dbSDimitry Andric       if (State) {
14775ffd83dbSDimitry Andric         State =
14785ffd83dbSDimitry Andric             SameBuffer->BindExpr(CE, LCtx, Builder.makeZeroVal(CE->getType()));
14795ffd83dbSDimitry Andric         C.addTransition(State);
14800b57cec5SDimitry Andric       }
1481480093f4SDimitry Andric       return;
14820b57cec5SDimitry Andric     }
14830b57cec5SDimitry Andric 
1484480093f4SDimitry Andric     // If the two arguments might be different buffers, we have to check
1485480093f4SDimitry Andric     // the size of both of them.
14865ffd83dbSDimitry Andric     assert(NotSameBuffer);
1487bdd1243dSDimitry Andric     State = CheckBufferAccess(C, State, Right, Size, AccessKind::read, CK);
1488bdd1243dSDimitry Andric     State = CheckBufferAccess(C, State, Left, Size, AccessKind::read, CK);
14895ffd83dbSDimitry Andric     if (State) {
14900b57cec5SDimitry Andric       // The return value is the comparison result, which we don't know.
14915ffd83dbSDimitry Andric       SVal CmpV = Builder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
14925ffd83dbSDimitry Andric       State = State->BindExpr(CE, LCtx, CmpV);
14935ffd83dbSDimitry Andric       C.addTransition(State);
14940b57cec5SDimitry Andric     }
14950b57cec5SDimitry Andric   }
14960b57cec5SDimitry Andric }
14970b57cec5SDimitry Andric 
14980b57cec5SDimitry Andric void CStringChecker::evalstrLength(CheckerContext &C,
14990b57cec5SDimitry Andric                                    const CallExpr *CE) const {
15000b57cec5SDimitry Andric   // size_t strlen(const char *s);
15010b57cec5SDimitry Andric   evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
15020b57cec5SDimitry Andric }
15030b57cec5SDimitry Andric 
15040b57cec5SDimitry Andric void CStringChecker::evalstrnLength(CheckerContext &C,
15050b57cec5SDimitry Andric                                     const CallExpr *CE) const {
15060b57cec5SDimitry Andric   // size_t strnlen(const char *s, size_t maxlen);
15070b57cec5SDimitry Andric   evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
15080b57cec5SDimitry Andric }
15090b57cec5SDimitry Andric 
15100b57cec5SDimitry Andric void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
15110b57cec5SDimitry Andric                                          bool IsStrnlen) const {
15120b57cec5SDimitry Andric   CurrentFunctionDescription = "string length function";
15130b57cec5SDimitry Andric   ProgramStateRef state = C.getState();
15140b57cec5SDimitry Andric   const LocationContext *LCtx = C.getLocationContext();
15150b57cec5SDimitry Andric 
15160b57cec5SDimitry Andric   if (IsStrnlen) {
15170b57cec5SDimitry Andric     const Expr *maxlenExpr = CE->getArg(1);
15180b57cec5SDimitry Andric     SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
15190b57cec5SDimitry Andric 
15200b57cec5SDimitry Andric     ProgramStateRef stateZeroSize, stateNonZeroSize;
15210b57cec5SDimitry Andric     std::tie(stateZeroSize, stateNonZeroSize) =
15220b57cec5SDimitry Andric       assumeZero(C, state, maxlenVal, maxlenExpr->getType());
15230b57cec5SDimitry Andric 
15240b57cec5SDimitry Andric     // If the size can be zero, the result will be 0 in that case, and we don't
15250b57cec5SDimitry Andric     // have to check the string itself.
15260b57cec5SDimitry Andric     if (stateZeroSize) {
15270b57cec5SDimitry Andric       SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
15280b57cec5SDimitry Andric       stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
15290b57cec5SDimitry Andric       C.addTransition(stateZeroSize);
15300b57cec5SDimitry Andric     }
15310b57cec5SDimitry Andric 
15320b57cec5SDimitry Andric     // If the size is GUARANTEED to be zero, we're done!
15330b57cec5SDimitry Andric     if (!stateNonZeroSize)
15340b57cec5SDimitry Andric       return;
15350b57cec5SDimitry Andric 
15360b57cec5SDimitry Andric     // Otherwise, record the assumption that the size is nonzero.
15370b57cec5SDimitry Andric     state = stateNonZeroSize;
15380b57cec5SDimitry Andric   }
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric   // Check that the string argument is non-null.
15415ffd83dbSDimitry Andric   AnyArgExpr Arg = {CE->getArg(0), 0};
15425ffd83dbSDimitry Andric   SVal ArgVal = state->getSVal(Arg.Expression, LCtx);
15435ffd83dbSDimitry Andric   state = checkNonNull(C, state, Arg, ArgVal);
15440b57cec5SDimitry Andric 
15450b57cec5SDimitry Andric   if (!state)
15460b57cec5SDimitry Andric     return;
15470b57cec5SDimitry Andric 
15485ffd83dbSDimitry Andric   SVal strLength = getCStringLength(C, state, Arg.Expression, ArgVal);
15490b57cec5SDimitry Andric 
15500b57cec5SDimitry Andric   // If the argument isn't a valid C string, there's no valid state to
15510b57cec5SDimitry Andric   // transition to.
15520b57cec5SDimitry Andric   if (strLength.isUndef())
15530b57cec5SDimitry Andric     return;
15540b57cec5SDimitry Andric 
15550b57cec5SDimitry Andric   DefinedOrUnknownSVal result = UnknownVal();
15560b57cec5SDimitry Andric 
15570b57cec5SDimitry Andric   // If the check is for strnlen() then bind the return value to no more than
15580b57cec5SDimitry Andric   // the maxlen value.
15590b57cec5SDimitry Andric   if (IsStrnlen) {
15600b57cec5SDimitry Andric     QualType cmpTy = C.getSValBuilder().getConditionType();
15610b57cec5SDimitry Andric 
15620b57cec5SDimitry Andric     // It's a little unfortunate to be getting this again,
15630b57cec5SDimitry Andric     // but it's not that expensive...
15640b57cec5SDimitry Andric     const Expr *maxlenExpr = CE->getArg(1);
15650b57cec5SDimitry Andric     SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
15660b57cec5SDimitry Andric 
1567bdd1243dSDimitry Andric     std::optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1568bdd1243dSDimitry Andric     std::optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>();
15690b57cec5SDimitry Andric 
15700b57cec5SDimitry Andric     if (strLengthNL && maxlenValNL) {
15710b57cec5SDimitry Andric       ProgramStateRef stateStringTooLong, stateStringNotTooLong;
15720b57cec5SDimitry Andric 
15730b57cec5SDimitry Andric       // Check if the strLength is greater than the maxlen.
15740b57cec5SDimitry Andric       std::tie(stateStringTooLong, stateStringNotTooLong) = state->assume(
15750b57cec5SDimitry Andric           C.getSValBuilder()
15760b57cec5SDimitry Andric               .evalBinOpNN(state, BO_GT, *strLengthNL, *maxlenValNL, cmpTy)
15770b57cec5SDimitry Andric               .castAs<DefinedOrUnknownSVal>());
15780b57cec5SDimitry Andric 
15790b57cec5SDimitry Andric       if (stateStringTooLong && !stateStringNotTooLong) {
15800b57cec5SDimitry Andric         // If the string is longer than maxlen, return maxlen.
15810b57cec5SDimitry Andric         result = *maxlenValNL;
15820b57cec5SDimitry Andric       } else if (stateStringNotTooLong && !stateStringTooLong) {
15830b57cec5SDimitry Andric         // If the string is shorter than maxlen, return its length.
15840b57cec5SDimitry Andric         result = *strLengthNL;
15850b57cec5SDimitry Andric       }
15860b57cec5SDimitry Andric     }
15870b57cec5SDimitry Andric 
15880b57cec5SDimitry Andric     if (result.isUnknown()) {
15890b57cec5SDimitry Andric       // If we don't have enough information for a comparison, there's
15900b57cec5SDimitry Andric       // no guarantee the full string length will actually be returned.
15910b57cec5SDimitry Andric       // All we know is the return value is the min of the string length
15920b57cec5SDimitry Andric       // and the limit. This is better than nothing.
15930b57cec5SDimitry Andric       result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
15940b57cec5SDimitry Andric                                                    C.blockCount());
15950b57cec5SDimitry Andric       NonLoc resultNL = result.castAs<NonLoc>();
15960b57cec5SDimitry Andric 
15970b57cec5SDimitry Andric       if (strLengthNL) {
15980b57cec5SDimitry Andric         state = state->assume(C.getSValBuilder().evalBinOpNN(
15990b57cec5SDimitry Andric                                   state, BO_LE, resultNL, *strLengthNL, cmpTy)
16000b57cec5SDimitry Andric                                   .castAs<DefinedOrUnknownSVal>(), true);
16010b57cec5SDimitry Andric       }
16020b57cec5SDimitry Andric 
16030b57cec5SDimitry Andric       if (maxlenValNL) {
16040b57cec5SDimitry Andric         state = state->assume(C.getSValBuilder().evalBinOpNN(
16050b57cec5SDimitry Andric                                   state, BO_LE, resultNL, *maxlenValNL, cmpTy)
16060b57cec5SDimitry Andric                                   .castAs<DefinedOrUnknownSVal>(), true);
16070b57cec5SDimitry Andric       }
16080b57cec5SDimitry Andric     }
16090b57cec5SDimitry Andric 
16100b57cec5SDimitry Andric   } else {
16110b57cec5SDimitry Andric     // This is a plain strlen(), not strnlen().
16120b57cec5SDimitry Andric     result = strLength.castAs<DefinedOrUnknownSVal>();
16130b57cec5SDimitry Andric 
16140b57cec5SDimitry Andric     // If we don't know the length of the string, conjure a return
16150b57cec5SDimitry Andric     // value, so it can be used in constraints, at least.
16160b57cec5SDimitry Andric     if (result.isUnknown()) {
16170b57cec5SDimitry Andric       result = C.getSValBuilder().conjureSymbolVal(nullptr, CE, LCtx,
16180b57cec5SDimitry Andric                                                    C.blockCount());
16190b57cec5SDimitry Andric     }
16200b57cec5SDimitry Andric   }
16210b57cec5SDimitry Andric 
16220b57cec5SDimitry Andric   // Bind the return value.
16230b57cec5SDimitry Andric   assert(!result.isUnknown() && "Should have conjured a value by now");
16240b57cec5SDimitry Andric   state = state->BindExpr(CE, LCtx, result);
16250b57cec5SDimitry Andric   C.addTransition(state);
16260b57cec5SDimitry Andric }
16270b57cec5SDimitry Andric 
16280b57cec5SDimitry Andric void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
16290b57cec5SDimitry Andric   // char *strcpy(char *restrict dst, const char *restrict src);
16300b57cec5SDimitry Andric   evalStrcpyCommon(C, CE,
1631480093f4SDimitry Andric                    /* ReturnEnd = */ false,
1632480093f4SDimitry Andric                    /* IsBounded = */ false,
1633480093f4SDimitry Andric                    /* appendK = */ ConcatFnKind::none);
16340b57cec5SDimitry Andric }
16350b57cec5SDimitry Andric 
16360b57cec5SDimitry Andric void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
16370b57cec5SDimitry Andric   // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
16380b57cec5SDimitry Andric   evalStrcpyCommon(C, CE,
1639480093f4SDimitry Andric                    /* ReturnEnd = */ false,
1640480093f4SDimitry Andric                    /* IsBounded = */ true,
1641480093f4SDimitry Andric                    /* appendK = */ ConcatFnKind::none);
16420b57cec5SDimitry Andric }
16430b57cec5SDimitry Andric 
16440b57cec5SDimitry Andric void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
16450b57cec5SDimitry Andric   // char *stpcpy(char *restrict dst, const char *restrict src);
16460b57cec5SDimitry Andric   evalStrcpyCommon(C, CE,
1647480093f4SDimitry Andric                    /* ReturnEnd = */ true,
1648480093f4SDimitry Andric                    /* IsBounded = */ false,
1649480093f4SDimitry Andric                    /* appendK = */ ConcatFnKind::none);
16500b57cec5SDimitry Andric }
16510b57cec5SDimitry Andric 
16520b57cec5SDimitry Andric void CStringChecker::evalStrlcpy(CheckerContext &C, const CallExpr *CE) const {
1653480093f4SDimitry Andric   // size_t strlcpy(char *dest, const char *src, size_t size);
16540b57cec5SDimitry Andric   evalStrcpyCommon(C, CE,
1655480093f4SDimitry Andric                    /* ReturnEnd = */ true,
1656480093f4SDimitry Andric                    /* IsBounded = */ true,
1657480093f4SDimitry Andric                    /* appendK = */ ConcatFnKind::none,
16580b57cec5SDimitry Andric                    /* returnPtr = */ false);
16590b57cec5SDimitry Andric }
16600b57cec5SDimitry Andric 
16610b57cec5SDimitry Andric void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
16620b57cec5SDimitry Andric   // char *strcat(char *restrict s1, const char *restrict s2);
16630b57cec5SDimitry Andric   evalStrcpyCommon(C, CE,
1664480093f4SDimitry Andric                    /* ReturnEnd = */ false,
1665480093f4SDimitry Andric                    /* IsBounded = */ false,
1666480093f4SDimitry Andric                    /* appendK = */ ConcatFnKind::strcat);
16670b57cec5SDimitry Andric }
16680b57cec5SDimitry Andric 
16690b57cec5SDimitry Andric void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
16700b57cec5SDimitry Andric   // char *strncat(char *restrict s1, const char *restrict s2, size_t n);
16710b57cec5SDimitry Andric   evalStrcpyCommon(C, CE,
1672480093f4SDimitry Andric                    /* ReturnEnd = */ false,
1673480093f4SDimitry Andric                    /* IsBounded = */ true,
1674480093f4SDimitry Andric                    /* appendK = */ ConcatFnKind::strcat);
16750b57cec5SDimitry Andric }
16760b57cec5SDimitry Andric 
16770b57cec5SDimitry Andric void CStringChecker::evalStrlcat(CheckerContext &C, const CallExpr *CE) const {
1678480093f4SDimitry Andric   // size_t strlcat(char *dst, const char *src, size_t size);
1679480093f4SDimitry Andric   // It will append at most size - strlen(dst) - 1 bytes,
1680480093f4SDimitry Andric   // NULL-terminating the result.
16810b57cec5SDimitry Andric   evalStrcpyCommon(C, CE,
1682480093f4SDimitry Andric                    /* ReturnEnd = */ false,
1683480093f4SDimitry Andric                    /* IsBounded = */ true,
1684480093f4SDimitry Andric                    /* appendK = */ ConcatFnKind::strlcat,
16850b57cec5SDimitry Andric                    /* returnPtr = */ false);
16860b57cec5SDimitry Andric }
16870b57cec5SDimitry Andric 
16880b57cec5SDimitry Andric void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
1689480093f4SDimitry Andric                                       bool ReturnEnd, bool IsBounded,
1690480093f4SDimitry Andric                                       ConcatFnKind appendK,
1691480093f4SDimitry Andric                                       bool returnPtr) const {
1692480093f4SDimitry Andric   if (appendK == ConcatFnKind::none)
16930b57cec5SDimitry Andric     CurrentFunctionDescription = "string copy function";
1694480093f4SDimitry Andric   else
1695480093f4SDimitry Andric     CurrentFunctionDescription = "string concatenation function";
16965ffd83dbSDimitry Andric 
16970b57cec5SDimitry Andric   ProgramStateRef state = C.getState();
16980b57cec5SDimitry Andric   const LocationContext *LCtx = C.getLocationContext();
16990b57cec5SDimitry Andric 
17000b57cec5SDimitry Andric   // Check that the destination is non-null.
1701*06c3fb27SDimitry Andric   DestinationArgExpr Dst = {{CE->getArg(0), 0}};
17025ffd83dbSDimitry Andric   SVal DstVal = state->getSVal(Dst.Expression, LCtx);
17035ffd83dbSDimitry Andric   state = checkNonNull(C, state, Dst, DstVal);
17040b57cec5SDimitry Andric   if (!state)
17050b57cec5SDimitry Andric     return;
17060b57cec5SDimitry Andric 
17070b57cec5SDimitry Andric   // Check that the source is non-null.
1708*06c3fb27SDimitry Andric   SourceArgExpr srcExpr = {{CE->getArg(1), 1}};
17095ffd83dbSDimitry Andric   SVal srcVal = state->getSVal(srcExpr.Expression, LCtx);
17105ffd83dbSDimitry Andric   state = checkNonNull(C, state, srcExpr, srcVal);
17110b57cec5SDimitry Andric   if (!state)
17120b57cec5SDimitry Andric     return;
17130b57cec5SDimitry Andric 
17140b57cec5SDimitry Andric   // Get the string length of the source.
17155ffd83dbSDimitry Andric   SVal strLength = getCStringLength(C, state, srcExpr.Expression, srcVal);
1716bdd1243dSDimitry Andric   std::optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>();
1717480093f4SDimitry Andric 
1718480093f4SDimitry Andric   // Get the string length of the destination buffer.
17195ffd83dbSDimitry Andric   SVal dstStrLength = getCStringLength(C, state, Dst.Expression, DstVal);
1720bdd1243dSDimitry Andric   std::optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>();
17210b57cec5SDimitry Andric 
17220b57cec5SDimitry Andric   // If the source isn't a valid C string, give up.
17230b57cec5SDimitry Andric   if (strLength.isUndef())
17240b57cec5SDimitry Andric     return;
17250b57cec5SDimitry Andric 
17260b57cec5SDimitry Andric   SValBuilder &svalBuilder = C.getSValBuilder();
17270b57cec5SDimitry Andric   QualType cmpTy = svalBuilder.getConditionType();
17280b57cec5SDimitry Andric   QualType sizeTy = svalBuilder.getContext().getSizeType();
17290b57cec5SDimitry Andric 
17300b57cec5SDimitry Andric   // These two values allow checking two kinds of errors:
17310b57cec5SDimitry Andric   // - actual overflows caused by a source that doesn't fit in the destination
17320b57cec5SDimitry Andric   // - potential overflows caused by a bound that could exceed the destination
17330b57cec5SDimitry Andric   SVal amountCopied = UnknownVal();
17340b57cec5SDimitry Andric   SVal maxLastElementIndex = UnknownVal();
17350b57cec5SDimitry Andric   const char *boundWarning = nullptr;
17360b57cec5SDimitry Andric 
17375ffd83dbSDimitry Andric   // FIXME: Why do we choose the srcExpr if the access has no size?
17385ffd83dbSDimitry Andric   //  Note that the 3rd argument of the call would be the size parameter.
1739*06c3fb27SDimitry Andric   SizeArgExpr SrcExprAsSizeDummy = {
1740*06c3fb27SDimitry Andric       {srcExpr.Expression, srcExpr.ArgumentIndex}};
17415ffd83dbSDimitry Andric   state = CheckOverlap(
17425ffd83dbSDimitry Andric       C, state,
1743*06c3fb27SDimitry Andric       (IsBounded ? SizeArgExpr{{CE->getArg(2), 2}} : SrcExprAsSizeDummy), Dst,
1744480093f4SDimitry Andric       srcExpr);
17450b57cec5SDimitry Andric 
17460b57cec5SDimitry Andric   if (!state)
17470b57cec5SDimitry Andric     return;
17480b57cec5SDimitry Andric 
17490b57cec5SDimitry Andric   // If the function is strncpy, strncat, etc... it is bounded.
1750480093f4SDimitry Andric   if (IsBounded) {
17510b57cec5SDimitry Andric     // Get the max number of characters to copy.
1752*06c3fb27SDimitry Andric     SizeArgExpr lenExpr = {{CE->getArg(2), 2}};
17535ffd83dbSDimitry Andric     SVal lenVal = state->getSVal(lenExpr.Expression, LCtx);
17540b57cec5SDimitry Andric 
17550b57cec5SDimitry Andric     // Protect against misdeclared strncpy().
17565ffd83dbSDimitry Andric     lenVal =
17575ffd83dbSDimitry Andric         svalBuilder.evalCast(lenVal, sizeTy, lenExpr.Expression->getType());
17580b57cec5SDimitry Andric 
1759bdd1243dSDimitry Andric     std::optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>();
17600b57cec5SDimitry Andric 
17610b57cec5SDimitry Andric     // If we know both values, we might be able to figure out how much
17620b57cec5SDimitry Andric     // we're copying.
17630b57cec5SDimitry Andric     if (strLengthNL && lenValNL) {
1764480093f4SDimitry Andric       switch (appendK) {
1765480093f4SDimitry Andric       case ConcatFnKind::none:
1766480093f4SDimitry Andric       case ConcatFnKind::strcat: {
17670b57cec5SDimitry Andric         ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
17680b57cec5SDimitry Andric         // Check if the max number to copy is less than the length of the src.
17690b57cec5SDimitry Andric         // If the bound is equal to the source length, strncpy won't null-
17700b57cec5SDimitry Andric         // terminate the result!
17710b57cec5SDimitry Andric         std::tie(stateSourceTooLong, stateSourceNotTooLong) = state->assume(
1772480093f4SDimitry Andric             svalBuilder
1773480093f4SDimitry Andric                 .evalBinOpNN(state, BO_GE, *strLengthNL, *lenValNL, cmpTy)
17740b57cec5SDimitry Andric                 .castAs<DefinedOrUnknownSVal>());
17750b57cec5SDimitry Andric 
17760b57cec5SDimitry Andric         if (stateSourceTooLong && !stateSourceNotTooLong) {
1777480093f4SDimitry Andric           // Max number to copy is less than the length of the src, so the
1778480093f4SDimitry Andric           // actual strLength copied is the max number arg.
17790b57cec5SDimitry Andric           state = stateSourceTooLong;
17800b57cec5SDimitry Andric           amountCopied = lenVal;
17810b57cec5SDimitry Andric 
17820b57cec5SDimitry Andric         } else if (!stateSourceTooLong && stateSourceNotTooLong) {
17830b57cec5SDimitry Andric           // The source buffer entirely fits in the bound.
17840b57cec5SDimitry Andric           state = stateSourceNotTooLong;
17850b57cec5SDimitry Andric           amountCopied = strLength;
17860b57cec5SDimitry Andric         }
1787480093f4SDimitry Andric         break;
1788480093f4SDimitry Andric       }
1789480093f4SDimitry Andric       case ConcatFnKind::strlcat:
1790480093f4SDimitry Andric         if (!dstStrLengthNL)
1791480093f4SDimitry Andric           return;
1792480093f4SDimitry Andric 
1793480093f4SDimitry Andric         // amountCopied = min (size - dstLen - 1 , srcLen)
1794480093f4SDimitry Andric         SVal freeSpace = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1795480093f4SDimitry Andric                                                  *dstStrLengthNL, sizeTy);
179681ad6265SDimitry Andric         if (!isa<NonLoc>(freeSpace))
1797480093f4SDimitry Andric           return;
1798480093f4SDimitry Andric         freeSpace =
1799480093f4SDimitry Andric             svalBuilder.evalBinOp(state, BO_Sub, freeSpace,
1800480093f4SDimitry Andric                                   svalBuilder.makeIntVal(1, sizeTy), sizeTy);
1801bdd1243dSDimitry Andric         std::optional<NonLoc> freeSpaceNL = freeSpace.getAs<NonLoc>();
1802480093f4SDimitry Andric 
1803480093f4SDimitry Andric         // While unlikely, it is possible that the subtraction is
1804480093f4SDimitry Andric         // too complex to compute, let's check whether it succeeded.
1805480093f4SDimitry Andric         if (!freeSpaceNL)
1806480093f4SDimitry Andric           return;
1807480093f4SDimitry Andric         SVal hasEnoughSpace = svalBuilder.evalBinOpNN(
1808480093f4SDimitry Andric             state, BO_LE, *strLengthNL, *freeSpaceNL, cmpTy);
1809480093f4SDimitry Andric 
1810480093f4SDimitry Andric         ProgramStateRef TrueState, FalseState;
1811480093f4SDimitry Andric         std::tie(TrueState, FalseState) =
1812480093f4SDimitry Andric             state->assume(hasEnoughSpace.castAs<DefinedOrUnknownSVal>());
1813480093f4SDimitry Andric 
1814480093f4SDimitry Andric         // srcStrLength <= size - dstStrLength -1
1815480093f4SDimitry Andric         if (TrueState && !FalseState) {
1816480093f4SDimitry Andric           amountCopied = strLength;
18170b57cec5SDimitry Andric         }
18180b57cec5SDimitry Andric 
1819480093f4SDimitry Andric         // srcStrLength > size - dstStrLength -1
1820480093f4SDimitry Andric         if (!TrueState && FalseState) {
1821480093f4SDimitry Andric           amountCopied = freeSpace;
1822480093f4SDimitry Andric         }
1823480093f4SDimitry Andric 
1824480093f4SDimitry Andric         if (TrueState && FalseState)
1825480093f4SDimitry Andric           amountCopied = UnknownVal();
1826480093f4SDimitry Andric         break;
1827480093f4SDimitry Andric       }
1828480093f4SDimitry Andric     }
18290b57cec5SDimitry Andric     // We still want to know if the bound is known to be too large.
18300b57cec5SDimitry Andric     if (lenValNL) {
1831480093f4SDimitry Andric       switch (appendK) {
1832480093f4SDimitry Andric       case ConcatFnKind::strcat:
18330b57cec5SDimitry Andric         // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
18340b57cec5SDimitry Andric 
18350b57cec5SDimitry Andric         // Get the string length of the destination. If the destination is
18360b57cec5SDimitry Andric         // memory that can't have a string length, we shouldn't be copying
18370b57cec5SDimitry Andric         // into it anyway.
18380b57cec5SDimitry Andric         if (dstStrLength.isUndef())
18390b57cec5SDimitry Andric           return;
18400b57cec5SDimitry Andric 
1841480093f4SDimitry Andric         if (dstStrLengthNL) {
1842480093f4SDimitry Andric           maxLastElementIndex = svalBuilder.evalBinOpNN(
1843480093f4SDimitry Andric               state, BO_Add, *lenValNL, *dstStrLengthNL, sizeTy);
1844480093f4SDimitry Andric 
18450b57cec5SDimitry Andric           boundWarning = "Size argument is greater than the free space in the "
18460b57cec5SDimitry Andric                          "destination buffer";
18470b57cec5SDimitry Andric         }
1848480093f4SDimitry Andric         break;
1849480093f4SDimitry Andric       case ConcatFnKind::none:
1850480093f4SDimitry Andric       case ConcatFnKind::strlcat:
1851480093f4SDimitry Andric         // For strncpy and strlcat, this is just checking
1852480093f4SDimitry Andric         //  that lenVal <= sizeof(dst).
18530b57cec5SDimitry Andric         // (Yes, strncpy and strncat differ in how they treat termination.
18540b57cec5SDimitry Andric         // strncat ALWAYS terminates, but strncpy doesn't.)
18550b57cec5SDimitry Andric 
18560b57cec5SDimitry Andric         // We need a special case for when the copy size is zero, in which
18570b57cec5SDimitry Andric         // case strncpy will do no work at all. Our bounds check uses n-1
18580b57cec5SDimitry Andric         // as the last element accessed, so n == 0 is problematic.
18590b57cec5SDimitry Andric         ProgramStateRef StateZeroSize, StateNonZeroSize;
18600b57cec5SDimitry Andric         std::tie(StateZeroSize, StateNonZeroSize) =
18610b57cec5SDimitry Andric             assumeZero(C, state, *lenValNL, sizeTy);
18620b57cec5SDimitry Andric 
18630b57cec5SDimitry Andric         // If the size is known to be zero, we're done.
18640b57cec5SDimitry Andric         if (StateZeroSize && !StateNonZeroSize) {
18650b57cec5SDimitry Andric           if (returnPtr) {
18660b57cec5SDimitry Andric             StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
18670b57cec5SDimitry Andric           } else {
1868480093f4SDimitry Andric             if (appendK == ConcatFnKind::none) {
1869480093f4SDimitry Andric               // strlcpy returns strlen(src)
1870480093f4SDimitry Andric               StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, strLength);
1871480093f4SDimitry Andric             } else {
1872480093f4SDimitry Andric               // strlcat returns strlen(src) + strlen(dst)
1873480093f4SDimitry Andric               SVal retSize = svalBuilder.evalBinOp(
1874480093f4SDimitry Andric                   state, BO_Add, strLength, dstStrLength, sizeTy);
1875480093f4SDimitry Andric               StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, retSize);
1876480093f4SDimitry Andric             }
18770b57cec5SDimitry Andric           }
18780b57cec5SDimitry Andric           C.addTransition(StateZeroSize);
18790b57cec5SDimitry Andric           return;
18800b57cec5SDimitry Andric         }
18810b57cec5SDimitry Andric 
18820b57cec5SDimitry Andric         // Otherwise, go ahead and figure out the last element we'll touch.
18830b57cec5SDimitry Andric         // We don't record the non-zero assumption here because we can't
18840b57cec5SDimitry Andric         // be sure. We won't warn on a possible zero.
18850b57cec5SDimitry Andric         NonLoc one = svalBuilder.makeIntVal(1, sizeTy).castAs<NonLoc>();
1886480093f4SDimitry Andric         maxLastElementIndex =
1887480093f4SDimitry Andric             svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL, one, sizeTy);
18880b57cec5SDimitry Andric         boundWarning = "Size argument is greater than the length of the "
18890b57cec5SDimitry Andric                        "destination buffer";
1890480093f4SDimitry Andric         break;
18910b57cec5SDimitry Andric       }
18920b57cec5SDimitry Andric     }
18930b57cec5SDimitry Andric   } else {
18940b57cec5SDimitry Andric     // The function isn't bounded. The amount copied should match the length
18950b57cec5SDimitry Andric     // of the source buffer.
18960b57cec5SDimitry Andric     amountCopied = strLength;
18970b57cec5SDimitry Andric   }
18980b57cec5SDimitry Andric 
18990b57cec5SDimitry Andric   assert(state);
19000b57cec5SDimitry Andric 
19010b57cec5SDimitry Andric   // This represents the number of characters copied into the destination
19020b57cec5SDimitry Andric   // buffer. (It may not actually be the strlen if the destination buffer
19030b57cec5SDimitry Andric   // is not terminated.)
19040b57cec5SDimitry Andric   SVal finalStrLength = UnknownVal();
1905480093f4SDimitry Andric   SVal strlRetVal = UnknownVal();
1906480093f4SDimitry Andric 
1907480093f4SDimitry Andric   if (appendK == ConcatFnKind::none && !returnPtr) {
1908480093f4SDimitry Andric     // strlcpy returns the sizeof(src)
1909480093f4SDimitry Andric     strlRetVal = strLength;
1910480093f4SDimitry Andric   }
19110b57cec5SDimitry Andric 
19120b57cec5SDimitry Andric   // If this is an appending function (strcat, strncat...) then set the
19130b57cec5SDimitry Andric   // string length to strlen(src) + strlen(dst) since the buffer will
19140b57cec5SDimitry Andric   // ultimately contain both.
1915480093f4SDimitry Andric   if (appendK != ConcatFnKind::none) {
19160b57cec5SDimitry Andric     // Get the string length of the destination. If the destination is memory
19170b57cec5SDimitry Andric     // that can't have a string length, we shouldn't be copying into it anyway.
19180b57cec5SDimitry Andric     if (dstStrLength.isUndef())
19190b57cec5SDimitry Andric       return;
19200b57cec5SDimitry Andric 
1921480093f4SDimitry Andric     if (appendK == ConcatFnKind::strlcat && dstStrLengthNL && strLengthNL) {
1922480093f4SDimitry Andric       strlRetVal = svalBuilder.evalBinOpNN(state, BO_Add, *strLengthNL,
1923480093f4SDimitry Andric                                            *dstStrLengthNL, sizeTy);
1924480093f4SDimitry Andric     }
1925480093f4SDimitry Andric 
1926bdd1243dSDimitry Andric     std::optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>();
19270b57cec5SDimitry Andric 
19280b57cec5SDimitry Andric     // If we know both string lengths, we might know the final string length.
1929480093f4SDimitry Andric     if (amountCopiedNL && dstStrLengthNL) {
19300b57cec5SDimitry Andric       // Make sure the two lengths together don't overflow a size_t.
1931480093f4SDimitry Andric       state = checkAdditionOverflow(C, state, *amountCopiedNL, *dstStrLengthNL);
19320b57cec5SDimitry Andric       if (!state)
19330b57cec5SDimitry Andric         return;
19340b57cec5SDimitry Andric 
1935480093f4SDimitry Andric       finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *amountCopiedNL,
19360b57cec5SDimitry Andric                                                *dstStrLengthNL, sizeTy);
19370b57cec5SDimitry Andric     }
19380b57cec5SDimitry Andric 
19390b57cec5SDimitry Andric     // If we couldn't get a single value for the final string length,
19400b57cec5SDimitry Andric     // we can at least bound it by the individual lengths.
19410b57cec5SDimitry Andric     if (finalStrLength.isUnknown()) {
19420b57cec5SDimitry Andric       // Try to get a "hypothetical" string length symbol, which we can later
19430b57cec5SDimitry Andric       // set as a real value if that turns out to be the case.
19440b57cec5SDimitry Andric       finalStrLength = getCStringLength(C, state, CE, DstVal, true);
19450b57cec5SDimitry Andric       assert(!finalStrLength.isUndef());
19460b57cec5SDimitry Andric 
1947bdd1243dSDimitry Andric       if (std::optional<NonLoc> finalStrLengthNL =
1948bdd1243dSDimitry Andric               finalStrLength.getAs<NonLoc>()) {
1949480093f4SDimitry Andric         if (amountCopiedNL && appendK == ConcatFnKind::none) {
1950480093f4SDimitry Andric           // we overwrite dst string with the src
19510b57cec5SDimitry Andric           // finalStrLength >= srcStrLength
1952480093f4SDimitry Andric           SVal sourceInResult = svalBuilder.evalBinOpNN(
1953480093f4SDimitry Andric               state, BO_GE, *finalStrLengthNL, *amountCopiedNL, cmpTy);
19540b57cec5SDimitry Andric           state = state->assume(sourceInResult.castAs<DefinedOrUnknownSVal>(),
19550b57cec5SDimitry Andric                                 true);
19560b57cec5SDimitry Andric           if (!state)
19570b57cec5SDimitry Andric             return;
19580b57cec5SDimitry Andric         }
19590b57cec5SDimitry Andric 
1960480093f4SDimitry Andric         if (dstStrLengthNL && appendK != ConcatFnKind::none) {
1961480093f4SDimitry Andric           // we extend the dst string with the src
19620b57cec5SDimitry Andric           // finalStrLength >= dstStrLength
19630b57cec5SDimitry Andric           SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
19640b57cec5SDimitry Andric                                                       *finalStrLengthNL,
19650b57cec5SDimitry Andric                                                       *dstStrLengthNL,
19660b57cec5SDimitry Andric                                                       cmpTy);
19670b57cec5SDimitry Andric           state =
19680b57cec5SDimitry Andric               state->assume(destInResult.castAs<DefinedOrUnknownSVal>(), true);
19690b57cec5SDimitry Andric           if (!state)
19700b57cec5SDimitry Andric             return;
19710b57cec5SDimitry Andric         }
19720b57cec5SDimitry Andric       }
19730b57cec5SDimitry Andric     }
19740b57cec5SDimitry Andric 
19750b57cec5SDimitry Andric   } else {
19760b57cec5SDimitry Andric     // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
19770b57cec5SDimitry Andric     // the final string length will match the input string length.
19780b57cec5SDimitry Andric     finalStrLength = amountCopied;
19790b57cec5SDimitry Andric   }
19800b57cec5SDimitry Andric 
19810b57cec5SDimitry Andric   SVal Result;
19820b57cec5SDimitry Andric 
19830b57cec5SDimitry Andric   if (returnPtr) {
19840b57cec5SDimitry Andric     // The final result of the function will either be a pointer past the last
19850b57cec5SDimitry Andric     // copied element, or a pointer to the start of the destination buffer.
1986480093f4SDimitry Andric     Result = (ReturnEnd ? UnknownVal() : DstVal);
19870b57cec5SDimitry Andric   } else {
1988480093f4SDimitry Andric     if (appendK == ConcatFnKind::strlcat || appendK == ConcatFnKind::none)
1989480093f4SDimitry Andric       //strlcpy, strlcat
1990480093f4SDimitry Andric       Result = strlRetVal;
1991480093f4SDimitry Andric     else
19920b57cec5SDimitry Andric       Result = finalStrLength;
19930b57cec5SDimitry Andric   }
19940b57cec5SDimitry Andric 
19950b57cec5SDimitry Andric   assert(state);
19960b57cec5SDimitry Andric 
19970b57cec5SDimitry Andric   // If the destination is a MemRegion, try to check for a buffer overflow and
19980b57cec5SDimitry Andric   // record the new string length.
1999bdd1243dSDimitry Andric   if (std::optional<loc::MemRegionVal> dstRegVal =
20000b57cec5SDimitry Andric           DstVal.getAs<loc::MemRegionVal>()) {
20015ffd83dbSDimitry Andric     QualType ptrTy = Dst.Expression->getType();
20020b57cec5SDimitry Andric 
20030b57cec5SDimitry Andric     // If we have an exact value on a bounded copy, use that to check for
20040b57cec5SDimitry Andric     // overflows, rather than our estimate about how much is actually copied.
2005bdd1243dSDimitry Andric     if (std::optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) {
20065ffd83dbSDimitry Andric       SVal maxLastElement =
20075ffd83dbSDimitry Andric           svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal, *maxLastNL, ptrTy);
20085ffd83dbSDimitry Andric 
20095ffd83dbSDimitry Andric       state = CheckLocation(C, state, Dst, maxLastElement, AccessKind::write);
20100b57cec5SDimitry Andric       if (!state)
20110b57cec5SDimitry Andric         return;
20120b57cec5SDimitry Andric     }
20130b57cec5SDimitry Andric 
20140b57cec5SDimitry Andric     // Then, if the final length is known...
2015bdd1243dSDimitry Andric     if (std::optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) {
20160b57cec5SDimitry Andric       SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
20170b57cec5SDimitry Andric           *knownStrLength, ptrTy);
20180b57cec5SDimitry Andric 
20190b57cec5SDimitry Andric       // ...and we haven't checked the bound, we'll check the actual copy.
20200b57cec5SDimitry Andric       if (!boundWarning) {
20215ffd83dbSDimitry Andric         state = CheckLocation(C, state, Dst, lastElement, AccessKind::write);
20220b57cec5SDimitry Andric         if (!state)
20230b57cec5SDimitry Andric           return;
20240b57cec5SDimitry Andric       }
20250b57cec5SDimitry Andric 
20260b57cec5SDimitry Andric       // If this is a stpcpy-style copy, the last element is the return value.
2027480093f4SDimitry Andric       if (returnPtr && ReturnEnd)
20280b57cec5SDimitry Andric         Result = lastElement;
20290b57cec5SDimitry Andric     }
20300b57cec5SDimitry Andric 
20310b57cec5SDimitry Andric     // Invalidate the destination (regular invalidation without pointer-escaping
20320b57cec5SDimitry Andric     // the address of the top-level region). This must happen before we set the
20330b57cec5SDimitry Andric     // C string length because invalidation will clear the length.
20340b57cec5SDimitry Andric     // FIXME: Even if we can't perfectly model the copy, we should see if we
20350b57cec5SDimitry Andric     // can use LazyCompoundVals to copy the source values into the destination.
20360b57cec5SDimitry Andric     // This would probably remove any existing bindings past the end of the
20370b57cec5SDimitry Andric     // string, but that's still an improvement over blank invalidation.
2038*06c3fb27SDimitry Andric     state = invalidateDestinationBufferBySize(C, state, Dst.Expression,
2039*06c3fb27SDimitry Andric                                               *dstRegVal, amountCopied,
2040*06c3fb27SDimitry Andric                                               C.getASTContext().getSizeType());
20410b57cec5SDimitry Andric 
20420b57cec5SDimitry Andric     // Invalidate the source (const-invalidation without const-pointer-escaping
20430b57cec5SDimitry Andric     // the address of the top-level region).
2044*06c3fb27SDimitry Andric     state = invalidateSourceBuffer(C, state, srcExpr.Expression, srcVal);
20450b57cec5SDimitry Andric 
20460b57cec5SDimitry Andric     // Set the C string length of the destination, if we know it.
2047480093f4SDimitry Andric     if (IsBounded && (appendK == ConcatFnKind::none)) {
20480b57cec5SDimitry Andric       // strncpy is annoying in that it doesn't guarantee to null-terminate
20490b57cec5SDimitry Andric       // the result string. If the original string didn't fit entirely inside
20500b57cec5SDimitry Andric       // the bound (including the null-terminator), we don't know how long the
20510b57cec5SDimitry Andric       // result is.
20520b57cec5SDimitry Andric       if (amountCopied != strLength)
20530b57cec5SDimitry Andric         finalStrLength = UnknownVal();
20540b57cec5SDimitry Andric     }
20550b57cec5SDimitry Andric     state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
20560b57cec5SDimitry Andric   }
20570b57cec5SDimitry Andric 
20580b57cec5SDimitry Andric   assert(state);
20590b57cec5SDimitry Andric 
20600b57cec5SDimitry Andric   if (returnPtr) {
20610b57cec5SDimitry Andric     // If this is a stpcpy-style copy, but we were unable to check for a buffer
20620b57cec5SDimitry Andric     // overflow, we still need a result. Conjure a return value.
2063480093f4SDimitry Andric     if (ReturnEnd && Result.isUnknown()) {
20640b57cec5SDimitry Andric       Result = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
20650b57cec5SDimitry Andric     }
20660b57cec5SDimitry Andric   }
20670b57cec5SDimitry Andric   // Set the return value.
20680b57cec5SDimitry Andric   state = state->BindExpr(CE, LCtx, Result);
20690b57cec5SDimitry Andric   C.addTransition(state);
20700b57cec5SDimitry Andric }
20710b57cec5SDimitry Andric 
20720b57cec5SDimitry Andric void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
20730b57cec5SDimitry Andric   //int strcmp(const char *s1, const char *s2);
2074480093f4SDimitry Andric   evalStrcmpCommon(C, CE, /* IsBounded = */ false, /* IgnoreCase = */ false);
20750b57cec5SDimitry Andric }
20760b57cec5SDimitry Andric 
20770b57cec5SDimitry Andric void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
20780b57cec5SDimitry Andric   //int strncmp(const char *s1, const char *s2, size_t n);
2079480093f4SDimitry Andric   evalStrcmpCommon(C, CE, /* IsBounded = */ true, /* IgnoreCase = */ false);
20800b57cec5SDimitry Andric }
20810b57cec5SDimitry Andric 
20820b57cec5SDimitry Andric void CStringChecker::evalStrcasecmp(CheckerContext &C,
20830b57cec5SDimitry Andric     const CallExpr *CE) const {
20840b57cec5SDimitry Andric   //int strcasecmp(const char *s1, const char *s2);
2085480093f4SDimitry Andric   evalStrcmpCommon(C, CE, /* IsBounded = */ false, /* IgnoreCase = */ true);
20860b57cec5SDimitry Andric }
20870b57cec5SDimitry Andric 
20880b57cec5SDimitry Andric void CStringChecker::evalStrncasecmp(CheckerContext &C,
20890b57cec5SDimitry Andric     const CallExpr *CE) const {
20900b57cec5SDimitry Andric   //int strncasecmp(const char *s1, const char *s2, size_t n);
2091480093f4SDimitry Andric   evalStrcmpCommon(C, CE, /* IsBounded = */ true, /* IgnoreCase = */ true);
20920b57cec5SDimitry Andric }
20930b57cec5SDimitry Andric 
20940b57cec5SDimitry Andric void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
2095480093f4SDimitry Andric     bool IsBounded, bool IgnoreCase) const {
20960b57cec5SDimitry Andric   CurrentFunctionDescription = "string comparison function";
20970b57cec5SDimitry Andric   ProgramStateRef state = C.getState();
20980b57cec5SDimitry Andric   const LocationContext *LCtx = C.getLocationContext();
20990b57cec5SDimitry Andric 
21000b57cec5SDimitry Andric   // Check that the first string is non-null
21015ffd83dbSDimitry Andric   AnyArgExpr Left = {CE->getArg(0), 0};
21025ffd83dbSDimitry Andric   SVal LeftVal = state->getSVal(Left.Expression, LCtx);
21035ffd83dbSDimitry Andric   state = checkNonNull(C, state, Left, LeftVal);
21040b57cec5SDimitry Andric   if (!state)
21050b57cec5SDimitry Andric     return;
21060b57cec5SDimitry Andric 
21070b57cec5SDimitry Andric   // Check that the second string is non-null.
21085ffd83dbSDimitry Andric   AnyArgExpr Right = {CE->getArg(1), 1};
21095ffd83dbSDimitry Andric   SVal RightVal = state->getSVal(Right.Expression, LCtx);
21105ffd83dbSDimitry Andric   state = checkNonNull(C, state, Right, RightVal);
21110b57cec5SDimitry Andric   if (!state)
21120b57cec5SDimitry Andric     return;
21130b57cec5SDimitry Andric 
21140b57cec5SDimitry Andric   // Get the string length of the first string or give up.
21155ffd83dbSDimitry Andric   SVal LeftLength = getCStringLength(C, state, Left.Expression, LeftVal);
21165ffd83dbSDimitry Andric   if (LeftLength.isUndef())
21170b57cec5SDimitry Andric     return;
21180b57cec5SDimitry Andric 
21190b57cec5SDimitry Andric   // Get the string length of the second string or give up.
21205ffd83dbSDimitry Andric   SVal RightLength = getCStringLength(C, state, Right.Expression, RightVal);
21215ffd83dbSDimitry Andric   if (RightLength.isUndef())
21220b57cec5SDimitry Andric     return;
21230b57cec5SDimitry Andric 
21240b57cec5SDimitry Andric   // If we know the two buffers are the same, we know the result is 0.
21250b57cec5SDimitry Andric   // First, get the two buffers' addresses. Another checker will have already
21260b57cec5SDimitry Andric   // made sure they're not undefined.
21275ffd83dbSDimitry Andric   DefinedOrUnknownSVal LV = LeftVal.castAs<DefinedOrUnknownSVal>();
21285ffd83dbSDimitry Andric   DefinedOrUnknownSVal RV = RightVal.castAs<DefinedOrUnknownSVal>();
21290b57cec5SDimitry Andric 
21300b57cec5SDimitry Andric   // See if they are the same.
21310b57cec5SDimitry Andric   SValBuilder &svalBuilder = C.getSValBuilder();
21320b57cec5SDimitry Andric   DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
21330b57cec5SDimitry Andric   ProgramStateRef StSameBuf, StNotSameBuf;
21340b57cec5SDimitry Andric   std::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
21350b57cec5SDimitry Andric 
21360b57cec5SDimitry Andric   // If the two arguments might be the same buffer, we know the result is 0,
21370b57cec5SDimitry Andric   // and we only need to check one size.
21380b57cec5SDimitry Andric   if (StSameBuf) {
21390b57cec5SDimitry Andric     StSameBuf = StSameBuf->BindExpr(CE, LCtx,
21400b57cec5SDimitry Andric         svalBuilder.makeZeroVal(CE->getType()));
21410b57cec5SDimitry Andric     C.addTransition(StSameBuf);
21420b57cec5SDimitry Andric 
21430b57cec5SDimitry Andric     // If the two arguments are GUARANTEED to be the same, we're done!
21440b57cec5SDimitry Andric     if (!StNotSameBuf)
21450b57cec5SDimitry Andric       return;
21460b57cec5SDimitry Andric   }
21470b57cec5SDimitry Andric 
21480b57cec5SDimitry Andric   assert(StNotSameBuf);
21490b57cec5SDimitry Andric   state = StNotSameBuf;
21500b57cec5SDimitry Andric 
21510b57cec5SDimitry Andric   // At this point we can go about comparing the two buffers.
21520b57cec5SDimitry Andric   // For now, we only do this if they're both known string literals.
21530b57cec5SDimitry Andric 
21540b57cec5SDimitry Andric   // Attempt to extract string literals from both expressions.
21555ffd83dbSDimitry Andric   const StringLiteral *LeftStrLiteral =
21565ffd83dbSDimitry Andric       getCStringLiteral(C, state, Left.Expression, LeftVal);
21575ffd83dbSDimitry Andric   const StringLiteral *RightStrLiteral =
21585ffd83dbSDimitry Andric       getCStringLiteral(C, state, Right.Expression, RightVal);
21590b57cec5SDimitry Andric   bool canComputeResult = false;
21600b57cec5SDimitry Andric   SVal resultVal = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx,
21610b57cec5SDimitry Andric       C.blockCount());
21620b57cec5SDimitry Andric 
21635ffd83dbSDimitry Andric   if (LeftStrLiteral && RightStrLiteral) {
21645ffd83dbSDimitry Andric     StringRef LeftStrRef = LeftStrLiteral->getString();
21655ffd83dbSDimitry Andric     StringRef RightStrRef = RightStrLiteral->getString();
21660b57cec5SDimitry Andric 
2167480093f4SDimitry Andric     if (IsBounded) {
21680b57cec5SDimitry Andric       // Get the max number of characters to compare.
21690b57cec5SDimitry Andric       const Expr *lenExpr = CE->getArg(2);
21700b57cec5SDimitry Andric       SVal lenVal = state->getSVal(lenExpr, LCtx);
21710b57cec5SDimitry Andric 
21720b57cec5SDimitry Andric       // If the length is known, we can get the right substrings.
21730b57cec5SDimitry Andric       if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
21740b57cec5SDimitry Andric         // Create substrings of each to compare the prefix.
21755ffd83dbSDimitry Andric         LeftStrRef = LeftStrRef.substr(0, (size_t)len->getZExtValue());
21765ffd83dbSDimitry Andric         RightStrRef = RightStrRef.substr(0, (size_t)len->getZExtValue());
21770b57cec5SDimitry Andric         canComputeResult = true;
21780b57cec5SDimitry Andric       }
21790b57cec5SDimitry Andric     } else {
21800b57cec5SDimitry Andric       // This is a normal, unbounded strcmp.
21810b57cec5SDimitry Andric       canComputeResult = true;
21820b57cec5SDimitry Andric     }
21830b57cec5SDimitry Andric 
21840b57cec5SDimitry Andric     if (canComputeResult) {
21850b57cec5SDimitry Andric       // Real strcmp stops at null characters.
21865ffd83dbSDimitry Andric       size_t s1Term = LeftStrRef.find('\0');
21870b57cec5SDimitry Andric       if (s1Term != StringRef::npos)
21885ffd83dbSDimitry Andric         LeftStrRef = LeftStrRef.substr(0, s1Term);
21890b57cec5SDimitry Andric 
21905ffd83dbSDimitry Andric       size_t s2Term = RightStrRef.find('\0');
21910b57cec5SDimitry Andric       if (s2Term != StringRef::npos)
21925ffd83dbSDimitry Andric         RightStrRef = RightStrRef.substr(0, s2Term);
21930b57cec5SDimitry Andric 
21940b57cec5SDimitry Andric       // Use StringRef's comparison methods to compute the actual result.
2195fe6060f1SDimitry Andric       int compareRes = IgnoreCase ? LeftStrRef.compare_insensitive(RightStrRef)
21965ffd83dbSDimitry Andric                                   : LeftStrRef.compare(RightStrRef);
21970b57cec5SDimitry Andric 
21980b57cec5SDimitry Andric       // The strcmp function returns an integer greater than, equal to, or less
21990b57cec5SDimitry Andric       // than zero, [c11, p7.24.4.2].
22000b57cec5SDimitry Andric       if (compareRes == 0) {
22010b57cec5SDimitry Andric         resultVal = svalBuilder.makeIntVal(compareRes, CE->getType());
22020b57cec5SDimitry Andric       }
22030b57cec5SDimitry Andric       else {
22040b57cec5SDimitry Andric         DefinedSVal zeroVal = svalBuilder.makeIntVal(0, CE->getType());
22050b57cec5SDimitry Andric         // Constrain strcmp's result range based on the result of StringRef's
22060b57cec5SDimitry Andric         // comparison methods.
2207bdd1243dSDimitry Andric         BinaryOperatorKind op = (compareRes > 0) ? BO_GT : BO_LT;
22080b57cec5SDimitry Andric         SVal compareWithZero =
22090b57cec5SDimitry Andric           svalBuilder.evalBinOp(state, op, resultVal, zeroVal,
22100b57cec5SDimitry Andric               svalBuilder.getConditionType());
22110b57cec5SDimitry Andric         DefinedSVal compareWithZeroVal = compareWithZero.castAs<DefinedSVal>();
22120b57cec5SDimitry Andric         state = state->assume(compareWithZeroVal, true);
22130b57cec5SDimitry Andric       }
22140b57cec5SDimitry Andric     }
22150b57cec5SDimitry Andric   }
22160b57cec5SDimitry Andric 
22170b57cec5SDimitry Andric   state = state->BindExpr(CE, LCtx, resultVal);
22180b57cec5SDimitry Andric 
22190b57cec5SDimitry Andric   // Record this as a possible path.
22200b57cec5SDimitry Andric   C.addTransition(state);
22210b57cec5SDimitry Andric }
22220b57cec5SDimitry Andric 
22230b57cec5SDimitry Andric void CStringChecker::evalStrsep(CheckerContext &C, const CallExpr *CE) const {
22240b57cec5SDimitry Andric   // char *strsep(char **stringp, const char *delim);
22255e801ac6SDimitry Andric   // Verify whether the search string parameter matches the return type.
2226*06c3fb27SDimitry Andric   SourceArgExpr SearchStrPtr = {{CE->getArg(0), 0}};
22275ffd83dbSDimitry Andric 
22285ffd83dbSDimitry Andric   QualType CharPtrTy = SearchStrPtr.Expression->getType()->getPointeeType();
22290b57cec5SDimitry Andric   if (CharPtrTy.isNull() ||
22300b57cec5SDimitry Andric       CE->getType().getUnqualifiedType() != CharPtrTy.getUnqualifiedType())
22310b57cec5SDimitry Andric     return;
22320b57cec5SDimitry Andric 
22330b57cec5SDimitry Andric   CurrentFunctionDescription = "strsep()";
22340b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
22350b57cec5SDimitry Andric   const LocationContext *LCtx = C.getLocationContext();
22360b57cec5SDimitry Andric 
22370b57cec5SDimitry Andric   // Check that the search string pointer is non-null (though it may point to
22380b57cec5SDimitry Andric   // a null string).
22395ffd83dbSDimitry Andric   SVal SearchStrVal = State->getSVal(SearchStrPtr.Expression, LCtx);
22405ffd83dbSDimitry Andric   State = checkNonNull(C, State, SearchStrPtr, SearchStrVal);
22410b57cec5SDimitry Andric   if (!State)
22420b57cec5SDimitry Andric     return;
22430b57cec5SDimitry Andric 
22440b57cec5SDimitry Andric   // Check that the delimiter string is non-null.
22455ffd83dbSDimitry Andric   AnyArgExpr DelimStr = {CE->getArg(1), 1};
22465ffd83dbSDimitry Andric   SVal DelimStrVal = State->getSVal(DelimStr.Expression, LCtx);
22475ffd83dbSDimitry Andric   State = checkNonNull(C, State, DelimStr, DelimStrVal);
22480b57cec5SDimitry Andric   if (!State)
22490b57cec5SDimitry Andric     return;
22500b57cec5SDimitry Andric 
22510b57cec5SDimitry Andric   SValBuilder &SVB = C.getSValBuilder();
22520b57cec5SDimitry Andric   SVal Result;
2253bdd1243dSDimitry Andric   if (std::optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) {
22540b57cec5SDimitry Andric     // Get the current value of the search string pointer, as a char*.
22550b57cec5SDimitry Andric     Result = State->getSVal(*SearchStrLoc, CharPtrTy);
22560b57cec5SDimitry Andric 
22570b57cec5SDimitry Andric     // Invalidate the search string, representing the change of one delimiter
22580b57cec5SDimitry Andric     // character to NUL.
2259*06c3fb27SDimitry Andric     // As the replacement never overflows, do not invalidate its super region.
2260*06c3fb27SDimitry Andric     State = invalidateDestinationBufferNeverOverflows(
2261*06c3fb27SDimitry Andric         C, State, SearchStrPtr.Expression, Result);
22620b57cec5SDimitry Andric 
22630b57cec5SDimitry Andric     // Overwrite the search string pointer. The new value is either an address
22640b57cec5SDimitry Andric     // further along in the same string, or NULL if there are no more tokens.
22650b57cec5SDimitry Andric     State = State->bindLoc(*SearchStrLoc,
22660b57cec5SDimitry Andric         SVB.conjureSymbolVal(getTag(),
22670b57cec5SDimitry Andric           CE,
22680b57cec5SDimitry Andric           LCtx,
22690b57cec5SDimitry Andric           CharPtrTy,
22700b57cec5SDimitry Andric           C.blockCount()),
22710b57cec5SDimitry Andric         LCtx);
22720b57cec5SDimitry Andric   } else {
22730b57cec5SDimitry Andric     assert(SearchStrVal.isUnknown());
22740b57cec5SDimitry Andric     // Conjure a symbolic value. It's the best we can do.
22750b57cec5SDimitry Andric     Result = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
22760b57cec5SDimitry Andric   }
22770b57cec5SDimitry Andric 
22780b57cec5SDimitry Andric   // Set the return value, and finish.
22790b57cec5SDimitry Andric   State = State->BindExpr(CE, LCtx, Result);
22800b57cec5SDimitry Andric   C.addTransition(State);
22810b57cec5SDimitry Andric }
22820b57cec5SDimitry Andric 
22830b57cec5SDimitry Andric // These should probably be moved into a C++ standard library checker.
22840b57cec5SDimitry Andric void CStringChecker::evalStdCopy(CheckerContext &C, const CallExpr *CE) const {
22850b57cec5SDimitry Andric   evalStdCopyCommon(C, CE);
22860b57cec5SDimitry Andric }
22870b57cec5SDimitry Andric 
22880b57cec5SDimitry Andric void CStringChecker::evalStdCopyBackward(CheckerContext &C,
22890b57cec5SDimitry Andric     const CallExpr *CE) const {
22900b57cec5SDimitry Andric   evalStdCopyCommon(C, CE);
22910b57cec5SDimitry Andric }
22920b57cec5SDimitry Andric 
22930b57cec5SDimitry Andric void CStringChecker::evalStdCopyCommon(CheckerContext &C,
22940b57cec5SDimitry Andric     const CallExpr *CE) const {
22950b57cec5SDimitry Andric   if (!CE->getArg(2)->getType()->isPointerType())
22960b57cec5SDimitry Andric     return;
22970b57cec5SDimitry Andric 
22980b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
22990b57cec5SDimitry Andric 
23000b57cec5SDimitry Andric   const LocationContext *LCtx = C.getLocationContext();
23010b57cec5SDimitry Andric 
23020b57cec5SDimitry Andric   // template <class _InputIterator, class _OutputIterator>
23030b57cec5SDimitry Andric   // _OutputIterator
23040b57cec5SDimitry Andric   // copy(_InputIterator __first, _InputIterator __last,
23050b57cec5SDimitry Andric   //        _OutputIterator __result)
23060b57cec5SDimitry Andric 
23070b57cec5SDimitry Andric   // Invalidate the destination buffer
23080b57cec5SDimitry Andric   const Expr *Dst = CE->getArg(2);
23090b57cec5SDimitry Andric   SVal DstVal = State->getSVal(Dst, LCtx);
2310*06c3fb27SDimitry Andric   // FIXME: As we do not know how many items are copied, we also invalidate the
2311*06c3fb27SDimitry Andric   // super region containing the target location.
2312*06c3fb27SDimitry Andric   State =
2313*06c3fb27SDimitry Andric       invalidateDestinationBufferAlwaysEscapeSuperRegion(C, State, Dst, DstVal);
23140b57cec5SDimitry Andric 
23150b57cec5SDimitry Andric   SValBuilder &SVB = C.getSValBuilder();
23160b57cec5SDimitry Andric 
23170b57cec5SDimitry Andric   SVal ResultVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount());
23180b57cec5SDimitry Andric   State = State->BindExpr(CE, LCtx, ResultVal);
23190b57cec5SDimitry Andric 
23200b57cec5SDimitry Andric   C.addTransition(State);
23210b57cec5SDimitry Andric }
23220b57cec5SDimitry Andric 
23230b57cec5SDimitry Andric void CStringChecker::evalMemset(CheckerContext &C, const CallExpr *CE) const {
23245ffd83dbSDimitry Andric   // void *memset(void *s, int c, size_t n);
23250b57cec5SDimitry Andric   CurrentFunctionDescription = "memory set function";
23260b57cec5SDimitry Andric 
2327*06c3fb27SDimitry Andric   DestinationArgExpr Buffer = {{CE->getArg(0), 0}};
23285ffd83dbSDimitry Andric   AnyArgExpr CharE = {CE->getArg(1), 1};
2329*06c3fb27SDimitry Andric   SizeArgExpr Size = {{CE->getArg(2), 2}};
23305ffd83dbSDimitry Andric 
23310b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
23320b57cec5SDimitry Andric 
23330b57cec5SDimitry Andric   // See if the size argument is zero.
23340b57cec5SDimitry Andric   const LocationContext *LCtx = C.getLocationContext();
23355ffd83dbSDimitry Andric   SVal SizeVal = C.getSVal(Size.Expression);
23365ffd83dbSDimitry Andric   QualType SizeTy = Size.Expression->getType();
23370b57cec5SDimitry Andric 
23385ffd83dbSDimitry Andric   ProgramStateRef ZeroSize, NonZeroSize;
23395ffd83dbSDimitry Andric   std::tie(ZeroSize, NonZeroSize) = assumeZero(C, State, SizeVal, SizeTy);
23400b57cec5SDimitry Andric 
23410b57cec5SDimitry Andric   // Get the value of the memory area.
23425ffd83dbSDimitry Andric   SVal BufferPtrVal = C.getSVal(Buffer.Expression);
23430b57cec5SDimitry Andric 
23440b57cec5SDimitry Andric   // If the size is zero, there won't be any actual memory access, so
23455ffd83dbSDimitry Andric   // just bind the return value to the buffer and return.
23465ffd83dbSDimitry Andric   if (ZeroSize && !NonZeroSize) {
23475ffd83dbSDimitry Andric     ZeroSize = ZeroSize->BindExpr(CE, LCtx, BufferPtrVal);
23485ffd83dbSDimitry Andric     C.addTransition(ZeroSize);
23490b57cec5SDimitry Andric     return;
23500b57cec5SDimitry Andric   }
23510b57cec5SDimitry Andric 
23520b57cec5SDimitry Andric   // Ensure the memory area is not null.
23530b57cec5SDimitry Andric   // If it is NULL there will be a NULL pointer dereference.
23545ffd83dbSDimitry Andric   State = checkNonNull(C, NonZeroSize, Buffer, BufferPtrVal);
23550b57cec5SDimitry Andric   if (!State)
23560b57cec5SDimitry Andric     return;
23570b57cec5SDimitry Andric 
23585ffd83dbSDimitry Andric   State = CheckBufferAccess(C, State, Buffer, Size, AccessKind::write);
23590b57cec5SDimitry Andric   if (!State)
23600b57cec5SDimitry Andric     return;
23610b57cec5SDimitry Andric 
23620b57cec5SDimitry Andric   // According to the values of the arguments, bind the value of the second
23630b57cec5SDimitry Andric   // argument to the destination buffer and set string length, or just
23640b57cec5SDimitry Andric   // invalidate the destination buffer.
23655ffd83dbSDimitry Andric   if (!memsetAux(Buffer.Expression, C.getSVal(CharE.Expression),
23665ffd83dbSDimitry Andric                  Size.Expression, C, State))
23670b57cec5SDimitry Andric     return;
23680b57cec5SDimitry Andric 
23695ffd83dbSDimitry Andric   State = State->BindExpr(CE, LCtx, BufferPtrVal);
23700b57cec5SDimitry Andric   C.addTransition(State);
23710b57cec5SDimitry Andric }
23720b57cec5SDimitry Andric 
23730b57cec5SDimitry Andric void CStringChecker::evalBzero(CheckerContext &C, const CallExpr *CE) const {
23740b57cec5SDimitry Andric   CurrentFunctionDescription = "memory clearance function";
23750b57cec5SDimitry Andric 
2376*06c3fb27SDimitry Andric   DestinationArgExpr Buffer = {{CE->getArg(0), 0}};
2377*06c3fb27SDimitry Andric   SizeArgExpr Size = {{CE->getArg(1), 1}};
23780b57cec5SDimitry Andric   SVal Zero = C.getSValBuilder().makeZeroVal(C.getASTContext().IntTy);
23790b57cec5SDimitry Andric 
23800b57cec5SDimitry Andric   ProgramStateRef State = C.getState();
23810b57cec5SDimitry Andric 
23820b57cec5SDimitry Andric   // See if the size argument is zero.
23835ffd83dbSDimitry Andric   SVal SizeVal = C.getSVal(Size.Expression);
23845ffd83dbSDimitry Andric   QualType SizeTy = Size.Expression->getType();
23850b57cec5SDimitry Andric 
23860b57cec5SDimitry Andric   ProgramStateRef StateZeroSize, StateNonZeroSize;
23870b57cec5SDimitry Andric   std::tie(StateZeroSize, StateNonZeroSize) =
23880b57cec5SDimitry Andric     assumeZero(C, State, SizeVal, SizeTy);
23890b57cec5SDimitry Andric 
23900b57cec5SDimitry Andric   // If the size is zero, there won't be any actual memory access,
23910b57cec5SDimitry Andric   // In this case we just return.
23920b57cec5SDimitry Andric   if (StateZeroSize && !StateNonZeroSize) {
23930b57cec5SDimitry Andric     C.addTransition(StateZeroSize);
23940b57cec5SDimitry Andric     return;
23950b57cec5SDimitry Andric   }
23960b57cec5SDimitry Andric 
23970b57cec5SDimitry Andric   // Get the value of the memory area.
23985ffd83dbSDimitry Andric   SVal MemVal = C.getSVal(Buffer.Expression);
23990b57cec5SDimitry Andric 
24000b57cec5SDimitry Andric   // Ensure the memory area is not null.
24010b57cec5SDimitry Andric   // If it is NULL there will be a NULL pointer dereference.
24025ffd83dbSDimitry Andric   State = checkNonNull(C, StateNonZeroSize, Buffer, MemVal);
24030b57cec5SDimitry Andric   if (!State)
24040b57cec5SDimitry Andric     return;
24050b57cec5SDimitry Andric 
24065ffd83dbSDimitry Andric   State = CheckBufferAccess(C, State, Buffer, Size, AccessKind::write);
24070b57cec5SDimitry Andric   if (!State)
24080b57cec5SDimitry Andric     return;
24090b57cec5SDimitry Andric 
24105ffd83dbSDimitry Andric   if (!memsetAux(Buffer.Expression, Zero, Size.Expression, C, State))
24110b57cec5SDimitry Andric     return;
24120b57cec5SDimitry Andric 
24130b57cec5SDimitry Andric   C.addTransition(State);
24140b57cec5SDimitry Andric }
24150b57cec5SDimitry Andric 
2416*06c3fb27SDimitry Andric void CStringChecker::evalSprintf(CheckerContext &C, const CallExpr *CE) const {
2417*06c3fb27SDimitry Andric   CurrentFunctionDescription = "'sprintf'";
2418*06c3fb27SDimitry Andric   bool IsBI = CE->getBuiltinCallee() == Builtin::BI__builtin___sprintf_chk;
2419*06c3fb27SDimitry Andric   evalSprintfCommon(C, CE, /* IsBounded */ false, IsBI);
2420*06c3fb27SDimitry Andric }
2421*06c3fb27SDimitry Andric 
2422*06c3fb27SDimitry Andric void CStringChecker::evalSnprintf(CheckerContext &C, const CallExpr *CE) const {
2423*06c3fb27SDimitry Andric   CurrentFunctionDescription = "'snprintf'";
2424*06c3fb27SDimitry Andric   bool IsBI = CE->getBuiltinCallee() == Builtin::BI__builtin___snprintf_chk;
2425*06c3fb27SDimitry Andric   evalSprintfCommon(C, CE, /* IsBounded */ true, IsBI);
2426*06c3fb27SDimitry Andric }
2427*06c3fb27SDimitry Andric 
2428*06c3fb27SDimitry Andric void CStringChecker::evalSprintfCommon(CheckerContext &C, const CallExpr *CE,
2429*06c3fb27SDimitry Andric                                        bool IsBounded, bool IsBuiltin) const {
2430*06c3fb27SDimitry Andric   ProgramStateRef State = C.getState();
2431*06c3fb27SDimitry Andric   DestinationArgExpr Dest = {{CE->getArg(0), 0}};
2432*06c3fb27SDimitry Andric 
2433*06c3fb27SDimitry Andric   const auto NumParams = CE->getCalleeDecl()->getAsFunction()->getNumParams();
2434*06c3fb27SDimitry Andric   assert(CE->getNumArgs() >= NumParams);
2435*06c3fb27SDimitry Andric 
2436*06c3fb27SDimitry Andric   const auto AllArguments =
2437*06c3fb27SDimitry Andric       llvm::make_range(CE->getArgs(), CE->getArgs() + CE->getNumArgs());
2438*06c3fb27SDimitry Andric   const auto VariadicArguments = drop_begin(enumerate(AllArguments), NumParams);
2439*06c3fb27SDimitry Andric 
2440*06c3fb27SDimitry Andric   for (const auto &[ArgIdx, ArgExpr] : VariadicArguments) {
2441*06c3fb27SDimitry Andric     // We consider only string buffers
2442*06c3fb27SDimitry Andric     if (const QualType type = ArgExpr->getType();
2443*06c3fb27SDimitry Andric         !type->isAnyPointerType() ||
2444*06c3fb27SDimitry Andric         !type->getPointeeType()->isAnyCharacterType())
2445*06c3fb27SDimitry Andric       continue;
2446*06c3fb27SDimitry Andric     SourceArgExpr Source = {{ArgExpr, unsigned(ArgIdx)}};
2447*06c3fb27SDimitry Andric 
2448*06c3fb27SDimitry Andric     // Ensure the buffers do not overlap.
2449*06c3fb27SDimitry Andric     SizeArgExpr SrcExprAsSizeDummy = {
2450*06c3fb27SDimitry Andric         {Source.Expression, Source.ArgumentIndex}};
2451*06c3fb27SDimitry Andric     State = CheckOverlap(
2452*06c3fb27SDimitry Andric         C, State,
2453*06c3fb27SDimitry Andric         (IsBounded ? SizeArgExpr{{CE->getArg(1), 1}} : SrcExprAsSizeDummy),
2454*06c3fb27SDimitry Andric         Dest, Source);
2455*06c3fb27SDimitry Andric     if (!State)
2456*06c3fb27SDimitry Andric       return;
2457*06c3fb27SDimitry Andric   }
2458*06c3fb27SDimitry Andric 
2459*06c3fb27SDimitry Andric   C.addTransition(State);
2460*06c3fb27SDimitry Andric }
2461*06c3fb27SDimitry Andric 
24620b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
24630b57cec5SDimitry Andric // The driver method, and other Checker callbacks.
24640b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
24650b57cec5SDimitry Andric 
24660b57cec5SDimitry Andric CStringChecker::FnCheck CStringChecker::identifyCall(const CallEvent &Call,
24670b57cec5SDimitry Andric                                                      CheckerContext &C) const {
24680b57cec5SDimitry Andric   const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
24690b57cec5SDimitry Andric   if (!CE)
24700b57cec5SDimitry Andric     return nullptr;
24710b57cec5SDimitry Andric 
24720b57cec5SDimitry Andric   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
24730b57cec5SDimitry Andric   if (!FD)
24740b57cec5SDimitry Andric     return nullptr;
24750b57cec5SDimitry Andric 
2476349cc55cSDimitry Andric   if (StdCopy.matches(Call))
24770b57cec5SDimitry Andric     return &CStringChecker::evalStdCopy;
2478349cc55cSDimitry Andric   if (StdCopyBackward.matches(Call))
24790b57cec5SDimitry Andric     return &CStringChecker::evalStdCopyBackward;
24800b57cec5SDimitry Andric 
24810b57cec5SDimitry Andric   // Pro-actively check that argument types are safe to do arithmetic upon.
24820b57cec5SDimitry Andric   // We do not want to crash if someone accidentally passes a structure
24830b57cec5SDimitry Andric   // into, say, a C++ overload of any of these functions. We could not check
24840b57cec5SDimitry Andric   // that for std::copy because they may have arguments of other types.
24850b57cec5SDimitry Andric   for (auto I : CE->arguments()) {
24860b57cec5SDimitry Andric     QualType T = I->getType();
24870b57cec5SDimitry Andric     if (!T->isIntegralOrEnumerationType() && !T->isPointerType())
24880b57cec5SDimitry Andric       return nullptr;
24890b57cec5SDimitry Andric   }
24900b57cec5SDimitry Andric 
24910b57cec5SDimitry Andric   const FnCheck *Callback = Callbacks.lookup(Call);
24920b57cec5SDimitry Andric   if (Callback)
24930b57cec5SDimitry Andric     return *Callback;
24940b57cec5SDimitry Andric 
24950b57cec5SDimitry Andric   return nullptr;
24960b57cec5SDimitry Andric }
24970b57cec5SDimitry Andric 
24980b57cec5SDimitry Andric bool CStringChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
24990b57cec5SDimitry Andric   FnCheck Callback = identifyCall(Call, C);
25000b57cec5SDimitry Andric 
25010b57cec5SDimitry Andric   // If the callee isn't a string function, let another checker handle it.
25020b57cec5SDimitry Andric   if (!Callback)
25030b57cec5SDimitry Andric     return false;
25040b57cec5SDimitry Andric 
25050b57cec5SDimitry Andric   // Check and evaluate the call.
25060b57cec5SDimitry Andric   const auto *CE = cast<CallExpr>(Call.getOriginExpr());
2507972a253aSDimitry Andric   Callback(this, C, CE);
25080b57cec5SDimitry Andric 
25090b57cec5SDimitry Andric   // If the evaluate call resulted in no change, chain to the next eval call
25100b57cec5SDimitry Andric   // handler.
25110b57cec5SDimitry Andric   // Note, the custom CString evaluation calls assume that basic safety
25120b57cec5SDimitry Andric   // properties are held. However, if the user chooses to turn off some of these
25130b57cec5SDimitry Andric   // checks, we ignore the issues and leave the call evaluation to a generic
25140b57cec5SDimitry Andric   // handler.
25150b57cec5SDimitry Andric   return C.isDifferent();
25160b57cec5SDimitry Andric }
25170b57cec5SDimitry Andric 
25180b57cec5SDimitry Andric void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
25190b57cec5SDimitry Andric   // Record string length for char a[] = "abc";
25200b57cec5SDimitry Andric   ProgramStateRef state = C.getState();
25210b57cec5SDimitry Andric 
25220b57cec5SDimitry Andric   for (const auto *I : DS->decls()) {
25230b57cec5SDimitry Andric     const VarDecl *D = dyn_cast<VarDecl>(I);
25240b57cec5SDimitry Andric     if (!D)
25250b57cec5SDimitry Andric       continue;
25260b57cec5SDimitry Andric 
25270b57cec5SDimitry Andric     // FIXME: Handle array fields of structs.
25280b57cec5SDimitry Andric     if (!D->getType()->isArrayType())
25290b57cec5SDimitry Andric       continue;
25300b57cec5SDimitry Andric 
25310b57cec5SDimitry Andric     const Expr *Init = D->getInit();
25320b57cec5SDimitry Andric     if (!Init)
25330b57cec5SDimitry Andric       continue;
25340b57cec5SDimitry Andric     if (!isa<StringLiteral>(Init))
25350b57cec5SDimitry Andric       continue;
25360b57cec5SDimitry Andric 
25370b57cec5SDimitry Andric     Loc VarLoc = state->getLValue(D, C.getLocationContext());
25380b57cec5SDimitry Andric     const MemRegion *MR = VarLoc.getAsRegion();
25390b57cec5SDimitry Andric     if (!MR)
25400b57cec5SDimitry Andric       continue;
25410b57cec5SDimitry Andric 
25420b57cec5SDimitry Andric     SVal StrVal = C.getSVal(Init);
25430b57cec5SDimitry Andric     assert(StrVal.isValid() && "Initializer string is unknown or undefined");
25440b57cec5SDimitry Andric     DefinedOrUnknownSVal strLength =
25450b57cec5SDimitry Andric       getCStringLength(C, state, Init, StrVal).castAs<DefinedOrUnknownSVal>();
25460b57cec5SDimitry Andric 
25470b57cec5SDimitry Andric     state = state->set<CStringLength>(MR, strLength);
25480b57cec5SDimitry Andric   }
25490b57cec5SDimitry Andric 
25500b57cec5SDimitry Andric   C.addTransition(state);
25510b57cec5SDimitry Andric }
25520b57cec5SDimitry Andric 
25530b57cec5SDimitry Andric ProgramStateRef
25540b57cec5SDimitry Andric CStringChecker::checkRegionChanges(ProgramStateRef state,
25550b57cec5SDimitry Andric     const InvalidatedSymbols *,
25560b57cec5SDimitry Andric     ArrayRef<const MemRegion *> ExplicitRegions,
25570b57cec5SDimitry Andric     ArrayRef<const MemRegion *> Regions,
25580b57cec5SDimitry Andric     const LocationContext *LCtx,
25590b57cec5SDimitry Andric     const CallEvent *Call) const {
25600b57cec5SDimitry Andric   CStringLengthTy Entries = state->get<CStringLength>();
25610b57cec5SDimitry Andric   if (Entries.isEmpty())
25620b57cec5SDimitry Andric     return state;
25630b57cec5SDimitry Andric 
25640b57cec5SDimitry Andric   llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
25650b57cec5SDimitry Andric   llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
25660b57cec5SDimitry Andric 
25670b57cec5SDimitry Andric   // First build sets for the changed regions and their super-regions.
2568*06c3fb27SDimitry Andric   for (const MemRegion *MR : Regions) {
25690b57cec5SDimitry Andric     Invalidated.insert(MR);
25700b57cec5SDimitry Andric 
25710b57cec5SDimitry Andric     SuperRegions.insert(MR);
25720b57cec5SDimitry Andric     while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
25730b57cec5SDimitry Andric       MR = SR->getSuperRegion();
25740b57cec5SDimitry Andric       SuperRegions.insert(MR);
25750b57cec5SDimitry Andric     }
25760b57cec5SDimitry Andric   }
25770b57cec5SDimitry Andric 
25780b57cec5SDimitry Andric   CStringLengthTy::Factory &F = state->get_context<CStringLength>();
25790b57cec5SDimitry Andric 
25800b57cec5SDimitry Andric   // Then loop over the entries in the current state.
2581*06c3fb27SDimitry Andric   for (const MemRegion *MR : llvm::make_first_range(Entries)) {
25820b57cec5SDimitry Andric     // Is this entry for a super-region of a changed region?
25830b57cec5SDimitry Andric     if (SuperRegions.count(MR)) {
25840b57cec5SDimitry Andric       Entries = F.remove(Entries, MR);
25850b57cec5SDimitry Andric       continue;
25860b57cec5SDimitry Andric     }
25870b57cec5SDimitry Andric 
25880b57cec5SDimitry Andric     // Is this entry for a sub-region of a changed region?
25890b57cec5SDimitry Andric     const MemRegion *Super = MR;
25900b57cec5SDimitry Andric     while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
25910b57cec5SDimitry Andric       Super = SR->getSuperRegion();
25920b57cec5SDimitry Andric       if (Invalidated.count(Super)) {
25930b57cec5SDimitry Andric         Entries = F.remove(Entries, MR);
25940b57cec5SDimitry Andric         break;
25950b57cec5SDimitry Andric       }
25960b57cec5SDimitry Andric     }
25970b57cec5SDimitry Andric   }
25980b57cec5SDimitry Andric 
25990b57cec5SDimitry Andric   return state->set<CStringLength>(Entries);
26000b57cec5SDimitry Andric }
26010b57cec5SDimitry Andric 
26020b57cec5SDimitry Andric void CStringChecker::checkLiveSymbols(ProgramStateRef state,
26030b57cec5SDimitry Andric     SymbolReaper &SR) const {
26040b57cec5SDimitry Andric   // Mark all symbols in our string length map as valid.
26050b57cec5SDimitry Andric   CStringLengthTy Entries = state->get<CStringLength>();
26060b57cec5SDimitry Andric 
2607*06c3fb27SDimitry Andric   for (SVal Len : llvm::make_second_range(Entries)) {
2608*06c3fb27SDimitry Andric     for (SymbolRef Sym : Len.symbols())
2609*06c3fb27SDimitry Andric       SR.markInUse(Sym);
26100b57cec5SDimitry Andric   }
26110b57cec5SDimitry Andric }
26120b57cec5SDimitry Andric 
26130b57cec5SDimitry Andric void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
26140b57cec5SDimitry Andric     CheckerContext &C) const {
26150b57cec5SDimitry Andric   ProgramStateRef state = C.getState();
26160b57cec5SDimitry Andric   CStringLengthTy Entries = state->get<CStringLength>();
26170b57cec5SDimitry Andric   if (Entries.isEmpty())
26180b57cec5SDimitry Andric     return;
26190b57cec5SDimitry Andric 
26200b57cec5SDimitry Andric   CStringLengthTy::Factory &F = state->get_context<CStringLength>();
2621*06c3fb27SDimitry Andric   for (auto [Reg, Len] : Entries) {
26220b57cec5SDimitry Andric     if (SymbolRef Sym = Len.getAsSymbol()) {
26230b57cec5SDimitry Andric       if (SR.isDead(Sym))
2624*06c3fb27SDimitry Andric         Entries = F.remove(Entries, Reg);
26250b57cec5SDimitry Andric     }
26260b57cec5SDimitry Andric   }
26270b57cec5SDimitry Andric 
26280b57cec5SDimitry Andric   state = state->set<CStringLength>(Entries);
26290b57cec5SDimitry Andric   C.addTransition(state);
26300b57cec5SDimitry Andric }
26310b57cec5SDimitry Andric 
26320b57cec5SDimitry Andric void ento::registerCStringModeling(CheckerManager &Mgr) {
26330b57cec5SDimitry Andric   Mgr.registerChecker<CStringChecker>();
26340b57cec5SDimitry Andric }
26350b57cec5SDimitry Andric 
26365ffd83dbSDimitry Andric bool ento::shouldRegisterCStringModeling(const CheckerManager &mgr) {
26370b57cec5SDimitry Andric   return true;
26380b57cec5SDimitry Andric }
26390b57cec5SDimitry Andric 
26400b57cec5SDimitry Andric #define REGISTER_CHECKER(name)                                                 \
26410b57cec5SDimitry Andric   void ento::register##name(CheckerManager &mgr) {                             \
26420b57cec5SDimitry Andric     CStringChecker *checker = mgr.getChecker<CStringChecker>();                \
26430b57cec5SDimitry Andric     checker->Filter.Check##name = true;                                        \
2644a7dea167SDimitry Andric     checker->Filter.CheckName##name = mgr.getCurrentCheckerName();             \
26450b57cec5SDimitry Andric   }                                                                            \
26460b57cec5SDimitry Andric                                                                                \
26475ffd83dbSDimitry Andric   bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
26480b57cec5SDimitry Andric 
26490b57cec5SDimitry Andric REGISTER_CHECKER(CStringNullArg)
26500b57cec5SDimitry Andric REGISTER_CHECKER(CStringOutOfBounds)
26510b57cec5SDimitry Andric REGISTER_CHECKER(CStringBufferOverlap)
26520b57cec5SDimitry Andric REGISTER_CHECKER(CStringNotNullTerm)
265381ad6265SDimitry Andric REGISTER_CHECKER(CStringUninitializedRead)
2654